Skip to content

ai-mcp: modern tool calls omit x-mcp-header parameter headers in 0.9.0 #1794

Closed

Description

@mintuhouse

TanStack AI version

@tanstack/ai-mcp@0.9.0. The same behavior was observed with 0.8.3.

Framework/Library version

@modelcontextprotocol/client@2.3.1, Deno 2.9.7, TypeScript 6.0.3, macOS arm64. The reproduction calls the MCP client directly and does not require React, an AI model, or a chat framework.

Describe the bug and the steps to reproduce it

Modern MCP tool calls made through createMCPClient().tools() omit the HTTP headers required by a tool's x-mcp-header input-schema annotations. The JSON arguments and standard Mcp-Name header are present, but the corresponding Mcp-Param-* headers are absent.

This breaks tools on GitHub's remote MCP server that declare owner and repo with x-mcp-header. For example, get_file_contents is rejected with HTTP 400, JSON-RPC error -32020, because Mcp-Param-owner and Mcp-Param-repo are missing. Discovery and tools without those annotated arguments, such as get_me and search_code, can succeed on the same connection. This is therefore easy to miss in a connection or basic tool smoke test.

  1. Connect using MCP protocol 2026-07-28 and StreamableHTTPClientTransport.
  2. Discover a tool whose input schema contains region: { type: "string", "x-mcp-header": "Region" }.
  3. Execute the discovered TanStack tool with { region: "eu" }.
  4. Inspect the outgoing tools/call headers. Mcp-Param-Region is missing.
  5. Repeat with the same transport fixture and native SDK Client.listTools() / Client.callTool(). The SDK sends Mcp-Param-Region: eu.

Expected: the TanStack adapter preserves the SDK's schema-driven header mirroring, so the same tool can be called successfully through either client.

Reproduced after installing @tanstack/ai-mcp@0.9.0. The fixture rejects a missing or mismatched header with HTTP 400 and error code -32020. Each path sent one tools/call:

Client Mcp-Name Mcp-Param-Region Result
TanStack 0.9.0 lookup absent (null) Fails with ProtocolError, message Missing or mismatched Mcp-Param-Region header
Native SDK 2.3.1 lookup eu Succeeds

Minimal reproducible example

The complete tested example is inline below. Save it as header-repro.mts and run it with Deno after resolving the pinned npm dependencies. It uses fake fetch responses and needs no MCP server, GitHub account, credentials, or AI model.

import { createMCPClient } from "npm:@tanstack/ai-mcp@0.9.0"
import { Client, StreamableHTTPClientTransport } from "npm:@modelcontextprotocol/client@2.3.1"

const tool = {
  name: "lookup",
  inputSchema: {
    type: "object" as const,
    properties: { region: { type: "string", "x-mcp-header": "Region" } },
    required: ["region"],
  },
}

async function reproduce(kind: "tanstack" | "native") {
  const calls: unknown[] = []
  const transport = new StreamableHTTPClientTransport(new URL("https://fixture.example/mcp"), {
    protocolVersion: "2026-07-28",
    fetch: async (_url, init) => {
      const body = JSON.parse(String(init?.body))
      const headers = new Headers(init?.headers)
      if (body.method === "tools/call") {
        const region = headers.get("Mcp-Param-Region")
        calls.push({ method: body.method, name: headers.get("Mcp-Name"), region })
        if (region !== body.params.arguments.region)
          return Response.json({ jsonrpc: "2.0", id: body.id, error: {
            code: -32020, message: "Missing or mismatched Mcp-Param-Region header",
          } }, { status: 400 })
      }
      const result = body.method === "server/discover"
        ? { supportedVersions: ["2026-07-28"], serverInfo: { name: "fixture", version: "1" }, capabilities: { tools: {} } }
        : body.method === "tools/list"
          ? { tools: [tool] }
          : { content: [{ type: "text", text: "ok" }] }
      return Response.json({ jsonrpc: "2.0", id: body.id, result: {
        resultType: "complete", ttlMs: 0, cacheScope: "private", ...result,
      } })
    },
  })
  let client: { close(): Promise<void> } | undefined
  try {
    if (kind === "tanstack") {
      const mcp = await createMCPClient({ transport })
      client = mcp
      const [remote] = await mcp.tools()
      await remote!.execute!({ region: "eu" }, undefined)
    } else {
      const mcp = new Client({ name: "control", version: "1" }, {
        versionNegotiation: { mode: { pin: "2026-07-28" } },
      })
      client = mcp
      await mcp.connect(transport)
      await mcp.listTools()
      await mcp.callTool({ name: "lookup", arguments: { region: "eu" } })
    }
    return { kind, success: true, calls }
  } catch (error) {
    return { kind, success: false, calls, error: String(error) }
  } finally {
    await client?.close()
  }
}

console.log(JSON.stringify(await Promise.all([reproduce("tanstack"), reproduce("native")]), null, 2))

Cause identified in the published source

In @tanstack/ai-mcp@0.9.0/src/tools.ts, callMcpTool sends modern calls through rawRequest, which calls transport.send(message) directly without send options. This bypasses Client.callTool, where SDK 2.3.1 derives the Mcp-Param-* headers from the tool definition. The transport adds standard protocol headers but cannot derive argument-specific headers without the schema.

Modern discovery in src/client.ts also uses a raw tools/list request rather than native Client.listTools(). A fix that routes calls through the SDK should therefore also populate its tool-definition cache or pass the explicit tool definition. The Streamable HTTP specification describes these required headers and their encoding.

The same rawRequest call also omits the transport's requestSignal option. It listens for abort to settle its own promise, but does not forward that signal through this send call. This is an adjacent source observation, not needed to reproduce the header failure, and may warrant separate cancellation coverage.

Possible fix and regression coverage

Could modern calls use the native SDK Client.callTool with the discovered toolDefinition and allowInputRequired: true, while preserving the adapter's manual input-required handling? This is a suggested direction, not a tested patch. The current follow-up call carrying inputResponses and requestState needs equivalent handling, and output validation, abort behavior, and retry semantics should remain intentional. Using native aggregated listTools() would also populate the SDK cache and retain its validation of header declarations.

The strict fixture above provides a regression test: a discovered modern tool with an x-mcp-header argument must send the matching Mcp-Param-* header and complete successfully. It currently fails with the latest TanStack release and passes with the native SDK.

Activity

  1. kyleromines commented on Oct 21, 2026

    @kyleromines

    @tombeckenham
    Still reproduces on 0.9.2 (published 2026-10-21): packages/ai-mcp/src is identical to 0.9.0, and dist/esm/tools.js still calls transport.send() with no options on the modern tools/call path.

    We hit this against GitHub's MCP server as:

    ProtocolError: header mismatch: missing Mcp-Param-repo header for parameter "repo"
    

    Here is a self-contained repro that needs no GitHub and no fake fetch. It uses only the official SDK server, which enforces SEP-2243 itself.

    Versions: @tanstack/ai-mcp 0.9.2, @modelcontextprotocol/client 2.2.0, @modelcontextprotocol/server 2.2.0, zod 4.6.7, Node 22.22.0.

    // repro.mjs — npm i @tanstack/ai-mcp@0.9.2 @tanstack/ai @modelcontextprotocol/client@2.2.0 @modelcontextprotocol/server@2.2.0 zod
    import { createServer } from 'node:http'
    import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'
    import { createMcpHandler, McpServer } from '@modelcontextprotocol/server'
    import { createMCPClient } from '@tanstack/ai-mcp'
    import { z } from 'zod'
    
    // A 2026-07-28-only server whose `repo` argument is mirrored into Mcp-Param-Repo.
    const build = () => {
      const server = new McpServer({ name: 'repro', version: '1.0.0' })
      server.registerTool(
        'get_repo',
        {
          description: 'Echoes the repo.',
          inputSchema: z.object({ repo: z.string().meta({ 'x-mcp-header': 'Repo' }) }),
        },
        ({ repo }) => ({ content: [{ type: 'text', text: `got ${repo}` }] }),
      )
      return server
    }
    const handler = createMcpHandler(build, { legacy: 'reject' })
    
    const seen = []
    const http = createServer(async (req, res) => {
      const chunks = []
      for await (const chunk of req) chunks.push(chunk)
      const body = Buffer.concat(chunks)
      const headers = new Headers()
      for (const [k, v] of Object.entries(req.headers)) if (typeof v === 'string') headers.set(k, v)
      if (req.method === 'POST' && body.includes('"tools/call"')) {
        seen.push(Object.fromEntries([...headers].filter(([k]) => k.startsWith('mcp-param-'))))
      }
      const response = await handler.fetch(
        new Request(`http://127.0.0.1${req.url}`, {
          method: req.method,
          headers,
          body: req.method === 'GET' || req.method === 'HEAD' ? undefined : body,
        }),
      )
      res.writeHead(response.status, Object.fromEntries(response.headers))
      if (!response.body) return res.end()
      for await (const chunk of response.body) res.write(chunk)
      res.end()
    })
    await new Promise((r) => http.listen(0, '127.0.0.1', r))
    const url = `http://127.0.0.1:${http.address().port}/mcp`
    
    // 1. The SDK's own client.
    const sdk = new Client({ name: 'sdk', version: '1.0.0' }, { versionNegotiation: { mode: 'auto' } })
    await sdk.connect(new StreamableHTTPClientTransport(new URL(url)))
    console.log('SDK era:', sdk.getProtocolEra())
    const direct = await sdk.callTool({ name: 'get_repo', arguments: { repo: 'octo/hello' } })
    console.log('SDK Client.callTool:', JSON.stringify(direct.content), 'Mcp-Param headers sent:', JSON.stringify(seen.at(-1)))
    await sdk.close()
    
    // 2. @tanstack/ai-mcp.
    const mcp = await createMCPClient({ transport: { type: 'http', url } })
    const tool = (await mcp.tools()).find((t) => t.name === 'get_repo')
    try {
      console.log('ai-mcp:', JSON.stringify(await tool.execute({ repo: 'octo/hello' })))
    } catch (error) {
      console.log('ai-mcp threw:', error.constructor.name, error.code, error.message)
    } finally {
      console.log('ai-mcp Mcp-Param headers sent:', JSON.stringify(seen.at(-1)))
      await mcp.close()
      http.closeAllConnections()
      http.close()
    }

    Output:

    SDK era: modern
    SDK Client.callTool: [{"type":"text","text":"got octo/hello"}] Mcp-Param headers sent: {"mcp-param-repo":"octo/hello"}
    ai-mcp threw: ProtocolError -32020 Bad Request: the request headers and body disagree: the body carries repo="octo/hello" but the Mcp-Param-Repo header is absent
    ai-mcp Mcp-Param headers sent: {}
    

    A few details that may help with the fix:

    1. Both raw call sites miss the header. callMcpTool uses rawRequest for the first modern tools/call and again for the retry after an input_required result, so a fix needs to cover both.
    2. The raw path also loses the SDK's recovery. Client.callTool recovers from a -32020: it evicts the cached tool definition, re-lists, and retries once. You can see this in the repro if you log requests. The SDK's first call goes out with no header because nothing is cached yet, is refused, and is retried after a tools/list. The raw path has neither the header nor the retry. ai-mcp had already listed the tools in the repro, so it had the schema and still sent no header.
    3. The transport already supports per-request headers. StreamableHTTPClientTransport.send(message, { headers }) merges them into the request and skips reserved names. Passing the Mcp-Param-* headers built from the listed tool's inputSchema would be enough. The catch is that the SDK's builder (scanXMcpHeaderDeclarations / buildMcpParamHeaders, including the =?base64?…?= encoding for non-ASCII values) isn't exported from @modelcontextprotocol/client. So the options are routing through callTool, as suggested above, asking the SDK to export the builder, or copying its rules.
  2. added a commit that references this issue on Oct 22, 2026
    52732c8
  3. added a commit that references this issue on Oct 22, 2026
    d980ce1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions