CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-anthropic-ai--claude-agent-sdk

SDK for building AI agents with Claude Code's capabilities to programmatically interact with Claude and build autonomous agents that can understand codebases, edit files, and execute workflows.

Overview
Eval results
Files

mcp.mddocs/apis/

MCP Integration

Model Context Protocol support for custom tools and servers.

Server Configuration

type McpServerConfig =
  | McpStdioServerConfig    // Subprocess
  | McpSSEServerConfig      // Server-Sent Events
  | McpHttpServerConfig     // HTTP
  | McpSdkServerConfigWithInstance; // In-process

interface McpStdioServerConfig {
  type?: 'stdio';
  command: string;
  args?: string[];
  env?: Record<string, string>;
}

interface McpSSEServerConfig {
  type: 'sse';
  url: string;
  headers?: Record<string, string>;
}

interface McpHttpServerConfig {
  type: 'http';
  url: string;
  headers?: Record<string, string>;
}

interface McpSdkServerConfigWithInstance {
  type: 'sdk';
  name: string;
  instance: McpServer;
}

Usage:

mcpServers: {
  'database': {
    command: 'node',
    args: ['./db-server.js'],
    env: {DB_HOST: 'localhost'}
  },
  'api': {
    type: 'http',
    url: 'http://localhost:3000/mcp',
    headers: {'Authorization': 'Bearer token'}
  },
  'realtime': {
    type: 'sse',
    url: 'http://localhost:4000/stream'
  }
}

Creating SDK Servers

function createSdkMcpServer(_options: {
  name: string;
  version?: string;
  tools?: Array<SdkMcpToolDefinition<any>>;
}): McpSdkServerConfigWithInstance;

Example:

import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
import { z } from 'zod';

const myServer = createSdkMcpServer({
  name: 'my-tools',
  version: '1.0.0',
  tools: [
    tool(
      'calculate',
      'Perform calculations',
      {
        op: z.enum(['add', 'sub', 'mul', 'div']),
        a: z.number(),
        b: z.number()
      },
      async (args) => {
        const ops = {add: (a, b) => a + b, sub: (a, b) => a - b, mul: (a, b) => a * b, div: (a, b) => a / b};
        const result = ops[args.op](args.a, args.b);
        return {content: [{type: 'text', text: `Result: ${result}`}]};
      }
    )
  ]
});

const result = query({
  prompt: 'Calculate 15 + 27',
  options: {mcpServers: {'my-tools': myServer}}
});

Defining Tools

function tool<Schema extends ZodRawShape>(
  _name: string,
  _description: string,
  _inputSchema: Schema,
  _handler: (args: z.infer<ZodObject<Schema>>, extra: unknown) => Promise<CallToolResult>
): SdkMcpToolDefinition<Schema>;

Examples:

import { tool } from '@anthropic-ai/claude-agent-sdk';
import { z } from 'zod';

// File search tool
const fileSearchTool = tool(
  'search_files',
  'Search files by pattern',
  {
    directory: z.string().describe('Directory to search'),
    pattern: z.string().describe('Glob pattern'),
    recursive: z.boolean().optional()
  },
  async (args) => {
    const files = await searchFiles(args.directory, args.pattern, args.recursive ?? false);
    return {
      content: [{type: 'text', text: `Found ${files.length} files:\n${files.join('\n')}`}]
    };
  }
);

// Database tool
const dbTool = tool(
  'query_db',
  'Execute SQL query',
  {
    query: z.string(),
    params: z.array(z.any()).optional()
  },
  async (args, extra) => {
    const results = await db.query(args.query, args.params);
    return {
      content: [{type: 'text', text: JSON.stringify(results, null, 2)}]
    };
  }
);

// Weather tool
const weatherTool = tool(
  'get_weather',
  'Get weather for location',
  {
    location: z.string(),
    units: z.enum(['celsius', 'fahrenheit']).optional()
  },
  async (args) => {
    const weather = await fetchWeather(args.location, args.units);
    return {
      content: [{type: 'text', text: `${weather.temperature}°, ${weather.condition}`}]
    };
  }
);

Server Status

const result = query({prompt: 'Task', options: {mcpServers: {...}}});

const status = await result.mcpServerStatus();
status.forEach(server => {
  console.log(`${server.name}: ${server.status}`);
  if (server.status === 'connected' && server.serverInfo) {
    console.log(`  Version: ${server.serverInfo.version}`);
  }
});

MCP Resources

// List resources (via ListMcpResourcesInput tool)
{server: 'my-server'}

// Read resource (via ReadMcpResourceInput tool)
{server: 'my-server', uri: 'file:///path/to/resource'}

Complete Example

import { query, createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
import { z } from 'zod';

// Define tools
const deployServer = createSdkMcpServer({
  name: 'deploy-tools',
  version: '1.0.0',
  tools: [
    tool(
      'read_config',
      'Read app configuration',
      {env: z.enum(['dev', 'staging', 'prod'])},
      async (args) => {
        const config = await loadConfig(args.env);
        return {content: [{type: 'text', text: JSON.stringify(config, null, 2)}]};
      }
    ),
    tool(
      'deploy',
      'Deploy app',
      {
        env: z.enum(['staging', 'prod']),
        version: z.string()
      },
      async (args) => {
        await deployApp(args.env, args.version);
        return {content: [{type: 'text', text: `Deployed ${args.version} to ${args.env}`}]};
      }
    )
  ]
});

// Use in query
const result = query({
  prompt: 'Read staging config and deploy v2.1.0',
  options: {
    mcpServers: {
      'deploy-tools': deployServer,
      'monitoring': {
        command: 'npx',
        args: ['-y', '@company/monitoring-mcp']
      }
    }
  }
});

for await (const msg of result) {
  if (msg.type === 'result') {
    console.log('Complete:', msg.result);
  }
}

Types

interface McpServerStatus {
  name: string;
  status: 'connected' | 'failed' | 'needs-auth' | 'pending';
  serverInfo?: {name: string; version: string};
}

Install with Tessl CLI

npx tessl i tessl/npm-anthropic-ai--claude-agent-sdk

docs

apis

agents.md

hooks.md

mcp.md

messages.md

options.md

permissions.md

query-api.md

sandbox.md

tools.md

index.md

patterns.md

quick-reference.md

types.md

tile.json