> ## 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: 10) - Maximum results per query",
    "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": [
    {
      "type": "excluded_tool_not_found | no_results | low_relevance",
      "message": "string - Warning message",
      "affectedTools": ["string (optional) - Affected tool names"]
    }
  ]
}
```

### 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": {
        "readOnlyHint": "boolean (optional)",
        "destructiveHint": "boolean (optional)",
        "idempotentHint": "boolean (optional)",
        "openWorldHint": "boolean (optional)"
      },
      "usageExamples": [
        {
          "description": "string - What this example demonstrates",
          "code": "string - JavaScript snippet using callTool()"
        }
      ]
    }
  ],
  "notFound": ["string (optional) - Tool names that weren't found"]
}
```

<Note>
  `usageExamples` returns up to 5 entries per tool. Each entry has a `description` and a `code` snippet that calls the tool via `callTool(...)` so the LLM can copy the pattern directly into a `codecall:execute` script.
</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
      },
      "usageExamples": [
        {
          "description": "List active users with pagination",
          "code": "const result = await callTool(\"users:list\", { status: \"active\", limit: 50 });"
        },
        {
          "description": "List admin users",
          "code": "const result = await callTool(\"users:list\", { role: \"admin\" });"
        },
        {
          "description": "List all users",
          "code": "const result = await callTool(\"users:list\", {});"
        }
      ]
    }],
    "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",
    "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

`codecall:invoke` returns the standard MCP `CallToolResult` — the same envelope a direct `tools/call` produces. Errors are surfaced via `isError: true` plus a textual `content` entry; there is no separate `{ status, error }` wrapper.

**Success:**

```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
{
  "content": [
    { "type": "text", "text": "..." }
  ],
  "structuredContent": "any (optional) - structured tool output when the tool declares an outputSchema",
  "isError": false
}
```

**Error:**

```json theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
{
  "content": [
    { "type": "text", "text": "Tool \"users:delete\" not found. Use codecall:search to discover available tools." }
  ],
  "isError": true
}
```

### 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"}}
  {
    "content": [
      {
        "type": "text",
        "text": "{\"id\":\"user-123\",\"email\":\"alice@example.com\",\"name\":\"Alice Smith\",\"role\":\"admin\",\"status\":\"active\"}"
      }
    ],
    "structuredContent": {
      "id": "user-123",
      "email": "alice@example.com",
      "name": "Alice Smith",
      "role": "admin",
      "status": "active"
    },
    "isError": false
  }
  ```
</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 `maxSteps` 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.run(`
      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 enclaveWithTools = new Enclave({ toolHandler: mockToolHandler });

    const result = await enclaveWithTools.run(`
      const data = await callTool('users:list', {});
      return data.users.length;
    `);

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

    enclaveWithTools.dispose();
  });
});
```

### 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/plugin-codecall';

@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 enclave = new Enclave();
    const result = await enclave.run(`
      eval('1 + 1');
    `);

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

    enclave.dispose();
  });

  it('should enforce iteration limit', async () => {
    // Note: maxIterations is the Enclave-direct option (max loop iterations
    // per loop). The CodeCall plugin maps its `vm.maxSteps` setting onto the
    // Enclave's `maxToolCalls` cap; set `maxIterations` directly when using
    // Enclave outside the plugin.
    const enclave = new Enclave({ maxIterations: 1000 });
    const result = await enclave.run(`
      let i = 0;
      for (const x of Array(100000)) { i++; }
      return i;
    `);

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

    enclave.dispose();
  });
});
```

### 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>
