diff --git a/MIGRATION.md b/MIGRATION.md index 463e035f..90766c19 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -278,7 +278,7 @@ new StackOneAPIError('Request failed', 400, { message: 'path.id is missing' }).m ## Schemas given to a model -**`toJsonSchema()` passes the served schema through**: root keywords such as `$schema`, `$defs`, `title` and `additionalProperties` reach the model as the server served them, and `required` is the served list, left out when it is missing or empty. `toOpenAI()`, `toAnthropic()`, `toOpenAIResponses()`, `toAISDK()` and `toClaudeAgentSdkTool()` fold a top-level `oneOf` / `anyOf` / `allOf`, which those APIs reject, into the root. +**`toJsonSchema()` passes the served schema through**: root keywords such as `$schema`, `$defs`, `title` and `additionalProperties` reach the model as the server served them, and `required` is the served list, left out when it is missing or empty. `toOpenAI()`, `toAnthropic()`, `toOpenAIResponses()`, `toAISDK()` and `toClaudeAgentSdk()` fold a top-level `oneOf` / `anyOf` / `allOf`, which those APIs reject, into the root. ## Hand-built tools and `ExecuteConfig` @@ -329,3 +329,22 @@ const hibobTools = tools.toArray().filter((tool) => tool.connector === 'hibob'); // 3.0 const hibobTools = await toolset.fetchTools({ providers: ['hibob'] }); ``` + +# Migrating from 3.x to 4.0 + +4.0 removes `BaseTool#toClaudeAgentSdkTool()`. `Tools#toClaudeAgentSdk()` keeps its name and arguments, and now returns a server whose tools carry their input schemas and receive the model's arguments. + +## Claude Agent SDK + +**`BaseTool#toClaudeAgentSdkTool()` is removed.** It built a definition for the Claude Agent SDK's `tool()`, which accepts only a Zod raw shape and drops a JSON schema, so a tool built from it reached Claude with no parameters. Pass the toolset to `toClaudeAgentSdk()` and hand the returned server to `mcpServers`: + +```typescript +// 3.x +const definition = await tool.toClaudeAgentSdkTool(); + +// 4.0 +const mcpServer = await tools.toClaudeAgentSdk(); +// query({ prompt, options: { mcpServers: { 'stackone-tools': mcpServer } } }) +``` + +To expose a subset of tools, filter first: `await tools.filter((tool) => tool.name.startsWith('bamboohr_')).toClaudeAgentSdk()`. diff --git a/README.md b/README.md index b4c99ca2..f3e7cca6 100644 --- a/README.md +++ b/README.md @@ -399,12 +399,12 @@ The catalog is cached per account scope and mode, so changing a filter never ref `tool.toJsonSchema()` is the schema the server served, verbatim — `$schema`, `$defs`, `$ref`, `title`, `additionalProperties`, top-level `oneOf`/`anyOf`/`allOf` and every nested constraint — with the served `required` list. It is a fresh copy each call. The framework adapters start from it and change only what the provider would otherwise reject: -| Adapter | Adjustment | -| ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `toJsonSchema()` | None: lossless. | -| `toOpenAI()`, `toAnthropic()`, `toClaudeAgentSdkTool()` | A top-level `oneOf`/`anyOf`/`allOf` is folded into the root: every branch's properties become root properties, and an `allOf` branch's `required` is merged in. OpenAI also rejects a top-level `enum`/`not`, so those are dropped. | -| `toOpenAIResponses()` | As above, not strict by default. `{ strict: true }` also gives the root `additionalProperties: false`, but OpenAI's strict mode additionally requires every property to be `required` and every nested object closed, which the SDK does not rewrite, so use it only for schemas that already meet that. | -| `toAISDK()` | As `toOpenAI()`, plus `additionalProperties: false` on the root. | +| Adapter | Adjustment | +| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `toJsonSchema()` | None: lossless. | +| `toOpenAI()`, `toAnthropic()`, `toClaudeAgentSdk()` | A top-level `oneOf`/`anyOf`/`allOf` is folded into the root: every branch's properties become root properties, and an `allOf` branch's `required` is merged in. OpenAI also rejects a top-level `enum`/`not`, so those are dropped. | +| `toOpenAIResponses()` | As above, not strict by default. `{ strict: true }` also gives the root `additionalProperties: false`, but OpenAI's strict mode additionally requires every property to be `required` and every nested object closed, which the SDK does not rewrite, so use it only for schemas that already meet that. | +| `toAISDK()` | As `toOpenAI()`, plus `additionalProperties: false` on the root. | ### Headers diff --git a/src/tool-optional-ai.test.ts b/src/tool-optional-ai.test.ts index 59652658..6351fc8e 100644 --- a/src/tool-optional-ai.test.ts +++ b/src/tool-optional-ai.test.ts @@ -21,7 +21,7 @@ describe('BaseTool optional ai peer handling', () => { vi.restoreAllMocks(); }); - it('rejects toClaudeAgentSdkTool with StackOneError and install hint when ai is unavailable', async () => { + it('rejects toAISDK with StackOneError and install hint when ai is unavailable', async () => { vi.doMock('./utils/try-import', () => ({ tryImport: vi.fn(async (moduleName: string, installHint: string) => { if (moduleName === 'ai') { @@ -37,8 +37,8 @@ describe('BaseTool optional ai peer handling', () => { const { BaseTool } = await import('./tool'); const tool = new BaseTool('test_tool', 'Test tool', createParameters(), createExecuteConfig()); - await expect(tool.toClaudeAgentSdkTool()).rejects.toBeInstanceOf(StackOneError); - await expect(tool.toClaudeAgentSdkTool()).rejects.toThrow( + await expect(tool.toAISDK()).rejects.toBeInstanceOf(StackOneError); + await expect(tool.toAISDK()).rejects.toThrow( `ai is not installed. Please install it with: npm install ai (requires ${peerDependencies.ai})`, ); }); diff --git a/src/tool.test.ts b/src/tool.test.ts index 9a6a46de..35a7f32e 100644 --- a/src/tool.test.ts +++ b/src/tool.test.ts @@ -1,3 +1,5 @@ +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; import { jsonSchema } from 'ai'; import { http } from 'msw'; @@ -153,10 +155,6 @@ describe('BaseTool', () => { return aiSdkJsonSchema(aiTool.inputSchema); }, ], - [ - 'toClaudeAgentSdkTool', - async () => aiSdkJsonSchema((await tool.toClaudeAgentSdkTool()).inputSchema), - ], ]; it.each(adapters)( @@ -262,20 +260,6 @@ describe('BaseTool', () => { expect((await tool.toAISDK()).test_tool?.execution).toBeUndefined(); expect((await tool.toAISDK({ executable: false })).test_tool?.execute).toBeUndefined(); }); - - it('serialises a Claude Agent SDK result for the model, bytes as base64', async () => { - const tool = simpleTool(); - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately bytes, not JSON - tool.execute = async () => ({ content: Buffer.from('%PDF') as never, ok: true }); - const definition = await tool.toClaudeAgentSdkTool(); - - const result = await definition.handler({}); - - expect(JSON.parse(result.content[0]?.text ?? '')).toEqual({ - content: Buffer.from('%PDF').toString('base64'), - ok: true, - }); - }); }); describe('StackOneMcpTool as an action tool', () => { @@ -756,6 +740,40 @@ describe('Tools', () => { expect(mcpServer.name).toBe('custom'); expect(mcpServer.instance).toBeDefined(); }); + + it('serves the Claude Agent SDK each schema and hands the tool the model arguments', async () => { + const rich = localTool('b', richSchema); + const seen: unknown[] = []; + rich.execute = async (args) => { + seen.push(args); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately bytes, not JSON + return { content: Buffer.from('%PDF') as never, ok: true }; + }; + const failing = named('c'); + failing.execute = async () => { + throw new StackOneAPIError('Upstream failed', 502, null); + }; + const { instance } = await new Tools([named('a'), rich, failing]).toClaudeAgentSdk(); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: 'test', version: '1.0.0' }); + await instance.connect(serverTransport); + await client.connect(clientTransport); + + const { tools } = await client.listTools(); + const result = await client.callTool({ name: 'b', arguments: { employee_id: 'emp_1' } }); + const failure = await client.callTool({ name: 'c', arguments: {} }); + await client.close(); + + expect(tools.map((tool) => tool.inputSchema)).toEqual( + [named('a'), rich, failing].map((tool) => tool.toAnthropic().input_schema), + ); + expect(seen).toEqual([{ employee_id: 'emp_1' }]); + expect(result).toEqual({ + content: [{ type: 'text', text: JSON.stringify({ content: 'JVBERg==', ok: true }) }], + }); + expect(failure).toMatchObject({ isError: true, content: [{ type: 'text' }] }); + expect(JSON.stringify(failure.content)).toContain('Upstream failed'); + }); }); describe('ToolParameters typing', () => { diff --git a/src/tool.ts b/src/tool.ts index 9861b513..3f7ab2d2 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -1,5 +1,12 @@ import type { Tool as AnthropicTool } from '@anthropic-ai/sdk/resources'; import type { McpSdkServerConfigWithInstance } from '@anthropic-ai/claude-agent-sdk'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { + CallToolRequestSchema, + ErrorCode, + ListToolsRequestSchema, + McpError, +} from '@modelcontextprotocol/sdk/types.js'; import type { ChatCompletionFunctionTool, ChatCompletionMessageToolCall, @@ -200,44 +207,6 @@ export class BaseTool { }; } - /** - * Convert the tool to Claude Agent SDK format. - * Returns a tool definition compatible with the Claude Agent SDK's tool() function. - * - * The schema is the one {@link toAnthropic} uses. Results are handed back as JSON text, with - * file bytes base64-encoded. - * - * @see https://docs.anthropic.com/en/docs/agents-and-tools/claude-agent-sdk - */ - async toClaudeAgentSdkTool(): Promise<{ - name: string; - description: string; - inputSchema: Record; - handler: ( - args: Record, - ) => Promise<{ content: Array<{ type: 'text'; text: string }> }>; - }> { - const ai = await tryImport( - 'ai', - `npm install ai (requires ${peerDependencies.ai})`, - ); - const inputSchema = ai.jsonSchema(this.#toProviderSchema()); - const execute = this.execute.bind(this); - - return { - name: this.name, - description: this.description, - inputSchema, - handler: async (args: Record) => { - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the SDK hands over the model's parsed JSON arguments - const result = await execute(args as JsonObject); - return { - content: [{ type: 'text' as const, text: serializeToolResult(result) }], - }; - }, - }; - } - /** * Convert the tool to AI SDK format. * @@ -870,35 +839,36 @@ export class Tools implements Iterable { options: ClaudeAgentSdkOptions = {}, ): Promise { const { serverName = 'stackone-tools', serverVersion = '1.0.0' } = options; + const tools = new Map(this.#uniqueTools().map((tool) => [tool.name, tool])); - // Import the Claude Agent SDK dynamically - const claudeAgentSdk = await tryImport( - '@anthropic-ai/claude-agent-sdk', - `npm install @anthropic-ai/claude-agent-sdk (requires ${peerDependencies['@anthropic-ai/claude-agent-sdk']})`, + // The SDK's tool() and createSdkMcpServer() take only Zod shapes: a JSON schema is dropped, + // leaving the model no parameters and the handler the request context instead of the arguments + const server = new McpServer( + { name: serverName, version: serverVersion }, + { capabilities: { tools: {} } }, ); - - // Convert all tools to Claude Agent SDK format - // We use type assertions here because the Zod types from our dynamic import - // don't perfectly match the Claude Agent SDK's expected types at compile time - const sdkTools = await Promise.all( - this.#uniqueTools().map(async (baseTool) => { - const toolDef = await baseTool.toClaudeAgentSdkTool(); - return claudeAgentSdk.tool( - toolDef.name, - toolDef.description, - // oxlint-disable-next-line typescript/no-explicit-any, typescript/no-unsafe-type-assertion -- the SDK types a Zod shape; it is handed the AI SDK's JSON schema - toolDef.inputSchema as any, - toolDef.handler, - ); - }), - ); - - // Create and return the MCP server - return claudeAgentSdk.createSdkMcpServer({ - name: serverName, - version: serverVersion, - tools: sdkTools, + const listed = [...tools.values()].map((tool) => { + const { name, description, input_schema } = tool.toAnthropic(); + return { name, description, inputSchema: input_schema }; }); + server.server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: listed })); + server.server.setRequestHandler(CallToolRequestSchema, async ({ params }) => { + const tool = tools.get(params.name); + if (tool === undefined) { + throw new McpError(ErrorCode.InvalidParams, `Tool ${params.name} not found`); + } + try { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the model's parsed JSON arguments + const result = await tool.execute((params.arguments ?? {}) as JsonObject); + return { content: [{ type: 'text', text: serializeToolResult(result) }] }; + } catch (error) { + // A tool error goes back to the model as a result it can read, not a protocol error + const text = error instanceof Error ? error.message : String(error); + return { content: [{ type: 'text', text }], isError: true }; + } + }); + + return { type: 'sdk', name: serverName, instance: server }; } /** diff --git a/tests/examples/claude-agent-sdk-integration.test.ts b/tests/examples/claude-agent-sdk-integration.test.ts index de44a900..a094e61b 100644 --- a/tests/examples/claude-agent-sdk-integration.test.ts +++ b/tests/examples/claude-agent-sdk-integration.test.ts @@ -1,19 +1,38 @@ /** * E2E test for claude-agent-sdk-integration.ts example * - * Tests the setup of StackOne tools with Claude Agent SDK. + * Tests the MCP server that `tools.toClaudeAgentSdk()` hands to the Claude Agent SDK. * * Note: The Claude Agent SDK spawns a subprocess to run claude-code, which * requires the ANTHROPIC_API_KEY environment variable and a running claude-code - * installation. This test validates the tool setup and MCP server creation, - * but does not test the actual query execution. + * installation. This test connects an MCP client to the server instead, which is + * what the SDK does, but does not test the actual query execution. */ -import { tool, createSdkMcpServer } from '@anthropic-ai/claude-agent-sdk'; -import { z } from 'zod'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js'; import { TEST_BASE_URL } from '../../mocks/constants'; import { StackOneToolSet } from '../../src'; +const fetchTools = async () => { + const toolset = new StackOneToolSet({ + accountId: 'your-bamboohr-account-id', + baseUrl: TEST_BASE_URL, + }); + return toolset.fetchTools(); +}; + +/** Connects an MCP client to the server, as the Claude Agent SDK does. */ +const connect = async (tools: Awaited>): Promise => { + const { instance } = await tools.toClaudeAgentSdk(); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: 'claude-agent-sdk', version: '1.0.0' }); + await instance.connect(serverTransport); + await client.connect(clientTransport); + return client; +}; + describe('claude-agent-sdk-integration example e2e', () => { beforeEach(() => { vi.stubEnv('STACKONE_API_KEY', 'test-key'); @@ -23,119 +42,39 @@ describe('claude-agent-sdk-integration example e2e', () => { vi.unstubAllEnvs(); }); - it('should fetch tools and create Claude Agent SDK tool wrapper', async () => { - const toolset = new StackOneToolSet({ - accountId: 'your-bamboohr-account-id', - baseUrl: TEST_BASE_URL, - }); - - // Fetch all tools for this account via MCP - const tools = await toolset.fetchTools(); - expect(tools.length).toBeGreaterThan(0); - - // Get a specific tool - const employeeTool = tools.getTool('bamboohr_get_employee'); - expect(employeeTool).toBeDefined(); - assert(employeeTool !== undefined); - - // Create Claude Agent SDK tool from StackOne tool - const getEmployeeTool = tool( - employeeTool.name, - employeeTool.description, - { - id: z.string().describe('The employee ID'), - }, - async (args) => { - const result = await employeeTool.execute(args); - return { - content: [{ type: 'text' as const, text: JSON.stringify(result) }], - }; - }, - ); - - expect(getEmployeeTool.name).toBe('bamboohr_get_employee'); - expect(getEmployeeTool.description).toContain('employee'); - expect(getEmployeeTool.inputSchema).toHaveProperty('id'); - expect(typeof getEmployeeTool.handler).toBe('function'); - }); - - it('should create MCP server with StackOne tools', async () => { - const toolset = new StackOneToolSet({ - accountId: 'your-bamboohr-account-id', - baseUrl: TEST_BASE_URL, - }); - - const tools = await toolset.fetchTools(); - const employeeTool = tools.getTool('bamboohr_get_employee'); - assert(employeeTool !== undefined); - - // Create Claude Agent SDK tool - const getEmployeeTool = tool( - employeeTool.name, - employeeTool.description, - { - id: z.string().describe('The employee ID'), - }, - async (args) => { - const result = await employeeTool.execute(args); - return { - content: [{ type: 'text' as const, text: JSON.stringify(result) }], - }; - }, - ); - - // Create an MCP server with the StackOne tool - const mcpServer = createSdkMcpServer({ - name: 'stackone-tools', - version: '1.0.0', - tools: [getEmployeeTool], - }); + it('creates an SDK MCP server from the fetched tools', async () => { + const mcpServer = await (await fetchTools()).toClaudeAgentSdk(); - // Verify MCP server was created - expect(mcpServer).toBeDefined(); - expect(mcpServer.name).toBe('stackone-tools'); + expect(mcpServer).toMatchObject({ type: 'sdk', name: 'stackone-tools' }); expect(mcpServer.instance).toBeDefined(); }); - it('should execute tool handler directly', async () => { - const toolset = new StackOneToolSet({ - accountId: 'your-bamboohr-account-id', - baseUrl: TEST_BASE_URL, - }); + it('serves each tool with its schema', async () => { + const tools = await fetchTools(); + const client = await connect(tools); + + const { tools: listed } = await client.listTools(); + await client.close(); - const tools = await toolset.fetchTools(); const employeeTool = tools.getTool('bamboohr_get_employee'); assert(employeeTool !== undefined); - - // Create Claude Agent SDK tool - const getEmployeeTool = tool( - employeeTool.name, - employeeTool.description, - { - id: z.string().describe('The employee ID'), - }, - async (args) => { - const result = await employeeTool.execute(args); - return { - content: [{ type: 'text' as const, text: JSON.stringify(result) }], - }; - }, + expect(listed.find((tool) => tool.name === 'bamboohr_get_employee')?.inputSchema).toEqual( + employeeTool.toAnthropic().input_schema, ); + }); - // Execute the tool handler directly - const result = await getEmployeeTool.handler( - { id: 'c28xIQaWQ6MzM5MzczMDA2NzMzMzkwNzIwNA' }, - {}, - ); + it('runs a tool call with the model arguments against StackOne', async () => { + const client = await connect(await fetchTools()); - expect(result).toBeDefined(); - expect(result.content).toHaveLength(1); - expect(result.content[0]?.type).toBe('text'); + const result = await client.callTool({ + name: 'bamboohr_get_employee', + arguments: { id: 'c28xIQaWQ6MzM5MzczMDA2NzMzMzkwNzIwNA' }, + }); + await client.close(); - // Parse the result text and verify it contains employee data - const textContent = result.content[0]; - assert(textContent?.type === 'text'); - const data = JSON.parse(textContent.text) as unknown; - expect(data).toMatchObject({ isError: false, result: { data: {} } }); + expect(result.isError).toBeUndefined(); + const [content] = CallToolResultSchema.parse(result).content; + assert(content?.type === 'text'); + expect(JSON.parse(content.text)).toMatchObject({ isError: false, result: { data: {} } }); }); });