> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentfront.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# API Reference

> Complete reference for CodeCall meta-tools - search, describe, execute, and invoke.

CodeCall exposes four meta-tools that replace direct tool access. This page documents the complete API for each tool with request/response schemas and examples.

***

## codecall:search

Search for tools by natural language query using semantic embeddings.

### Request Schema

```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
{
  "tool": "codecall:search",
  "input": {
    "queries": ["string (required) - Natural language search queries"],
    "topK": "number (optional, default: 5) - Maximum results to return",
    "appIds": ["string (optional) - Limit to specific apps"],
    "excludeToolNames": ["string (optional) - Tool names to exclude"],
    "minRelevanceScore": "number (optional) - Minimum relevance score threshold"
  }
}
```

### Response Schema

```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
{
  "tools": [
    {
      "name": "string - Tool name (e.g., 'users:list')",
      "appId": "string - Owning app ID",
      "description": "string - Tool description",
      "relevanceScore": "number - Relevance score (0-1)",
      "matchedQueries": ["string - Queries that matched this tool"]
    }
  ],
  "totalAvailableTools": "number - Total tools in index",
  "warnings": ["string (optional) - Any warnings about the search"]
}
```

### Examples

<CodeGroup>
  ```json Search All Apps theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
  {
    "tool": "codecall:search",
    "input": {
      "queries": ["get user profile information"],
      "topK": 5
    }
  }
  ```

  ```json Filter by App theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
  {
    "tool": "codecall:search",
    "input": {
      "queries": ["list all invoices"],
      "topK": 10,
      "appIds": ["billing", "payments"]
    }
  }
  ```
</CodeGroup>

### Response Example

```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
{
  "tools": [
    {
      "name": "users:getProfile",
      "appId": "user-service",
      "description": "Get user profile by ID with full details",
      "relevanceScore": 0.94,
      "matchedQueries": ["get user profile information"]
    },
    {
      "name": "users:list",
      "appId": "user-service",
      "description": "List all users with pagination and filtering",
      "relevanceScore": 0.78,
      "matchedQueries": ["get user profile information"]
    },
    {
      "name": "auth:whoami",
      "appId": "auth-service",
      "description": "Get current authenticated user info",
      "relevanceScore": 0.72,
      "matchedQueries": ["get user profile information"]
    }
  ],
  "totalAvailableTools": 156
}
```

### Search Strategy

CodeCall supports two embedding strategies:

| Strategy | Description                        | Best For                              |
| -------- | ---------------------------------- | ------------------------------------- |
| `tfidf`  | TF-IDF text matching (default)     | Fast, no model loading, works offline |
| `ml`     | Semantic embeddings via VectoriaDB | Better relevance, requires model      |

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
CodeCallPlugin.init({
  embedding: {
    strategy: 'tfidf',  // or 'ml'
  },
});
```

***

## codecall:describe

Get detailed schemas and documentation for specific tools.

### Request Schema

```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
{
  "tool": "codecall:describe",
  "input": {
    "toolNames": ["string (required) - Array of tool names to describe"]
  }
}
```

### Response Schema

```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
{
  "tools": [
    {
      "name": "string - Tool name",
      "appId": "string - Owning app ID",
      "description": "string - Full description",
      "inputSchema": { /* JSON Schema */ },
      "outputSchema": { /* JSON Schema or null */ },
      "annotations": {
        "destructiveHint": "boolean (optional)",
        "idempotentHint": "boolean (optional)",
        "openWorldHint": "boolean (optional)"
      },
      "examples": [
        {
          "description": "string - Example description",
          "input": { /* Example input arguments */ },
          "output": { /* Expected output */ }
        }
      ]
    }
  ],
  "notFound": ["string (optional) - Tool names that weren't found"]
}
```

<Note>
  `examples` returns up to 5 examples per tool. User-provided examples from the `@Tool` decorator take priority, with smart-generated examples filling remaining slots based on tool intent (create, list, get, update, delete, search).
</Note>

### Example

<CodeGroup>
  ```json Request theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
  {
    "tool": "codecall:describe",
    "input": {
      "toolNames": ["users:list", "users:getById"]
    }
  }
  ```

  ```json Response theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
  {
    "tools": [{
      "name": "users:list",
      "appId": "user-service",
      "description": "List users with optional filtering and pagination",
      "inputSchema": {
        "type": "object",
        "properties": {
          "status": {
            "type": "string",
            "enum": ["active", "inactive", "pending"],
            "description": "Filter by user status"
          },
          "role": {
          "type": "string",
          "enum": ["admin", "user", "guest"],
          "description": "Filter by role"
          },
          "limit": {
            "type": "number",
            "minimum": 1,
            "maximum": 100,
            "default": 20,
            "description": "Maximum results per page"
          },
          "offset": {
            "type": "number",
            "minimum": 0,
            "default": 0,
            "description": "Pagination offset"
          }
        }
      },
      "outputSchema": {
        "type": "object",
        "properties": {
          "users": {
            "type": "array",
            "items": {"$ref": "#/definitions/User"}
          },
          "total": {"type": "number"},
          "hasMore": {"type": "boolean"}
        }
      },
      "annotations": {
        "readOnlyHint": true
      },
      "examples": [
        {
          "description": "List active users with pagination",
          "input": { "status": "active", "limit": 50 },
          "output": { "users": [], "total": 0, "hasMore": false }
        },
        {
          "description": "List admin users",
          "input": { "role": "admin" },
          "output": { "users": [], "total": 0, "hasMore": false }
        },
        {
          "description": "List all users",
          "input": {},
          "output": { "users": [], "total": 0, "hasMore": false }
        }
      ]
    }],
    "notFound": []
  }
  ```
</CodeGroup>

### Security Note

<Warning>
  `codecall:describe` will not return information about CodeCall meta-tools themselves. Attempting to describe
  `codecall:execute` returns the tool in `notFound`.
</Warning>

***

## codecall:execute

Execute a JavaScript (AgentScript) plan that orchestrates multiple tools.

### Request Schema

```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
{
  "tool": "codecall:execute",
  "input": {
    "script": "string (required) - JavaScript code to execute",
    "context": { /* (optional) - Read-only context available as codecallContext */ },
    "allowedTools": ["string (optional) - Whitelist of allowed tool names"]
  }
}
```

### Response Schema

**Success:**

```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
{
  "status": "ok",
  "result": "any - Return value from script",
  "logs": ["string (optional) - Console output if enabled"]
}
```

**Error Responses:**

<AccordionGroup>
  <Accordion title="Syntax Error">
    ```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
    {
      "status": "syntax_error",
      "error": {
        "message": "Unexpected token at line 5",
        "location": {"line": 5, "column": 12}
      }
    }
    ```
  </Accordion>

  <Accordion title="Validation Error (AST)">
    ```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
    {
      "status": "illegal_access",
      "error": {
        "kind": "IllegalBuiltinAccess",
        "message": "Identifier 'eval' is not allowed in AgentScript"
      }
    }
    ```
  </Accordion>

  <Accordion title="Runtime Error">
    ```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
    {
      "status": "runtime_error",
      "error": {
        "source": "script",
        "message": "Cannot read property 'name' of undefined",
        "name": "TypeError"
      }
    }
    ```
  </Accordion>

  <Accordion title="Tool Error">
    ```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
    {
      "status": "tool_error",
      "error": {
        "source": "tool",
        "toolName": "users:list",
        "message": "Rate limit exceeded",
        "code": "RATE_LIMIT"
      }
    }
    ```
  </Accordion>

  <Accordion title="Timeout">
    ```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
    {
      "status": "timeout",
      "error": {
        "message": "Script execution timed out after 3500ms"
      }
    }
    ```
  </Accordion>
</AccordionGroup>

### Example

<CodeGroup>
  ```json Request theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
  {
    "tool": "codecall:execute",
    "input": {
      "script": "const users = await callTool('users:list', { status: 'active' });\nconst admins = users.users.filter(u => u.role === 'admin');\nreturn { adminCount: admins.length, admins: admins.map(a => a.email) };"
    }
  }
  ```

  ```json Response theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
  {
    "status": "ok",
    "result": {
      "adminCount": 3,
      "admins": ["alice@example.com", "bob@example.com", "charlie@example.com"]
    }
  }
  ```
</CodeGroup>

<Card title="AgentScript Guide" icon="scroll" href="/frontmcp/plugins/codecall/agentscript">
  For the complete scripting API (`callTool`, `getTool`, `codecallContext`, `__safe_parallel`), error handling patterns, and best practices, see the dedicated AgentScript guide.
</Card>

***

## codecall:invoke

Direct tool invocation without JavaScript execution. Useful for simple single-tool calls.

### Request Schema

```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
{
  "tool": "codecall:invoke",
  "input": {
    "tool": "string (required) - Tool name to invoke",
    "input": { /* (required) - Input to pass to the tool */ }
  }
}
```

### Response Schema

**Success:**

```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
{
  "status": "ok",
  "result": "any - Tool return value"
}
```

**Error:**

```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
{
  "status": "error",
  "error": {
    "code": "string - Error code",
    "message": "string - Error message"
  }
}
```

### Example

<CodeGroup>
  ```json Request theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
  {
    "tool": "codecall:invoke",
    "input": {
    "tool": "users:getById",
    "input": {"id": "user-123"}
  }
  }
  ```

  ```json Response theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
  {
    "status": "ok",
    "result": {
    "id": "user-123",
    "email": "alice@example.com",
    "name": "Alice Smith",
    "role": "admin",
    "status": "active"
  }
  }
  ```
</CodeGroup>

### When to Use Invoke vs Execute

| Use `codecall:invoke`              | Use `codecall:execute`        |
| ---------------------------------- | ----------------------------- |
| Single tool call                   | Multiple tool calls           |
| No data transformation needed      | Filter/join/transform results |
| Latency-sensitive (no VM overhead) | Complex orchestration logic   |
| Simple CRUD operations             | Conditional workflows         |

***

## Error Codes Reference

### Script Execution Errors

| Code                     | Status           | Description                    | Recovery                         |
| ------------------------ | ---------------- | ------------------------------ | -------------------------------- |
| `SYNTAX_ERROR`           | `syntax_error`   | JavaScript syntax error        | Fix syntax at indicated location |
| `VALIDATION_ERROR`       | `illegal_access` | AST validation failed          | Remove blocked construct         |
| `SELF_REFERENCE_BLOCKED` | `illegal_access` | Tried to call codecall:\* tool | Use regular tools only           |
| `TOOL_NOT_FOUND`         | `tool_error`     | Tool doesn't exist             | Check tool name spelling         |
| `ACCESS_DENIED`          | `tool_error`     | Tool not in allowedTools       | Add to allowlist                 |
| `EXECUTION_ERROR`        | `runtime_error`  | Runtime error in script        | Debug script logic               |
| `TIMEOUT`                | `timeout`        | Exceeded time limit            | Optimize or increase timeout     |
| `TOOL_EXECUTION_ERROR`   | `tool_error`     | Tool threw an error            | Check tool input                 |

***

## Error Handling

For error handling patterns including retry, fallback, and partial success strategies, see the [AgentScript Guide](/frontmcp/plugins/codecall/agentscript#error-handling-patterns).

***

## Debugging Guide

### Using console.log

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Enable in config
CodeCallPlugin.init({
  vm: { allowConsole: true }
});

// In script
const users = await callTool('users:list', { limit: 10 });
console.log('Fetched users:', users.length);

for (const user of users) {
  console.log('Processing:', user.id, user.email);
}

// Logs appear in response.logs array
```

### Interpreting Error Messages

<AccordionGroup>
  <Accordion title="Maximum iteration limit exceeded">
    **Cause:** Loop ran more than `maxIterations` times
    **Fix:** Use pagination or filter data before looping

    ```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
    // Bad: looping over potentially large dataset
    for (const item of items) { ... }

    // Good: paginate or limit
    const page = items.slice(0, 100);
    for (const item of page) { ... }
    ```
  </Accordion>

  <Accordion title="Maximum tool call limit exceeded">
    **Cause:** Script called more than `maxToolCalls` tools
    **Fix:** Batch operations or use `__safe_parallel`

    ```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
    // Bad: one tool call per item
    for (const id of ids) {
      await callTool('users:get', { id });
    }

    // Good: batch fetch
    const users = await callTool('users:getBatch', { ids });
    ```
  </Accordion>

  <Accordion title="Script execution timed out">
    **Cause:** Script ran longer than `timeoutMs`
    **Fix:** Optimize, use less data, or increase timeout

    ```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
    // Check preset timeout
    // locked_down: 2s, secure: 3.5s, balanced: 5s
    CodeCallPlugin.init({
      vm: { preset: 'balanced', timeoutMs: 8000 }
    });
    ```
  </Accordion>

  <Accordion title="Identifier 'X' is not allowed">
    **Cause:** Used a blocked identifier (eval, require, etc.)
    **Fix:** Use allowed alternatives

    ```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
    // Blocked
    eval('code');
    require('module');
    setTimeout(fn, 100);

    // Allowed
    // Use callTool for external operations
    await callTool('code:run', { script: 'code' });
    ```
  </Accordion>
</AccordionGroup>

### Development Mode

For easier debugging during development:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
CodeCallPlugin.init({
  vm: {
    preset: 'experimental',  // Longer timeouts, more iterations
    allowConsole: true,
  },
});
```

***

## Testing Strategy

### Unit Testing AgentScript

Use the Enclave library directly to test script execution in isolation:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { Enclave } from '@enclave-vm/core';

describe('AgentScript', () => {
  let enclave: Enclave;

  beforeEach(() => {
    enclave = new Enclave();
  });

  afterEach(() => {
    enclave.dispose();
  });

  it('should execute basic script', async () => {
    const result = await enclave.execute(`
      return 1 + 1;
    `);

    expect(result.success).toBe(true);
    expect(result.value).toBe(2);
  });

  it('should call tools', async () => {
    const mockToolHandler = jest.fn().mockResolvedValue({ users: [] });

    const result = await enclave.execute(`
      const data = await callTool('users:list', {});
      return data.users.length;
    `, { toolHandler: mockToolHandler });

    expect(mockToolHandler).toHaveBeenCalledWith('users:list', {});
    expect(result.value).toBe(0);
  });
});
```

### Integration Testing

For end-to-end tests, set up a FrontMCP app with CodeCallPlugin and invoke the meta-tools through your MCP test client:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { App, Tool, ToolContext } from '@frontmcp/sdk';
import { CodeCallPlugin } from '@frontmcp/plugins';

@App({ id: 'test-app', plugins: [CodeCallPlugin.init()] })
class TestApp {
  @Tool({ name: 'users:list' })
  async listUsers(ctx: ToolContext) {
    return [
      { id: '1', name: 'Alice' },
      { id: '2', name: 'Bob' },
    ];
  }
}

// Use your MCP test client to call codecall:execute
// and verify the response status and result
```

### Testing Security Rules

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
describe('Security', () => {
  it('should block eval', async () => {
    const result = await enclave.execute(`
      eval('1 + 1');
    `);

    expect(result.success).toBe(false);
    expect(result.error?.message).toContain('eval');
  });

  it('should enforce iteration limit', async () => {
    const result = await enclave.execute(`
      let i = 0;
      for (const x of Array(100000)) { i++; }
      return i;
    `, { config: { maxIterations: 1000 } });

    expect(result.success).toBe(false);
    expect(result.error?.message).toContain('iteration limit');
  });
});
```

### CI/CD Integration

```yaml theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
# .github/workflows/test.yml
name: Test CodeCall Scripts

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'

      - run: npm ci
      - run: npm test

      # Run CodeCall-specific security tests
      - run: npm run test:security
```

***

***

## Related

<CardGroup cols={2}>
  <Card title="AgentScript Guide" icon="scroll" href="/frontmcp/plugins/codecall/agentscript">
    Complete scripting API, error handling, and best practices
  </Card>

  <Card title="Configuration" icon="gear" href="/frontmcp/plugins/codecall/configuration">
    Configure meta-tool behavior and limits
  </Card>

  <Card title="Security Model" icon="shield" href="/frontmcp/plugins/codecall/security">
    How scripts are validated and sandboxed
  </Card>

  <Card title="Examples & Recipes" icon="flask" href="/frontmcp/plugins/codecall/examples">
    Real-world patterns using the meta-tools
  </Card>
</CardGroup>
