CopilotKit icon indicating copy to clipboard operation
CopilotKit copied to clipboard

🐛 Bug: Unable to make MCP Server tool calls with params

Open koikar opened this issue 6 months ago • 2 comments

♻️ Reproduction Steps

  1. Create fresh Nextjs app using npx create-next-app@latest
  2. Integrate copilotkit using the CLI npx copilotkit@latest init -m MCP
  3. Connect to Copilotkit cloud account.
🎉 Your CopilotKit setup is complete! 🎉

📋 Recap
  - CopilotKit has been added to your Next.js app.
  - With Copilot Cloud.
  1. Add a remote MCP Server via the cloud dashboard (I also tried adding the MCP Server directly inside the UI -> same result)
Image
  1. Open /copilotkit page and ask to get any documentation.
Image
  1. Tool gets called but errors.

How do I event start to debug this when using the cloud runtime?

Obviously the MCP Server works in any other MCP client like Claude, Cursor, MCP Inspector.

✅ Expected Behavior

The chat assistant should return a successful tool call.

❌ Actual Behavior

Name resolve-library-id

Parameters

{
  "libraryName": "zod"
}

Result

{
  "error": {
    "code": "HANDLER_ERROR",
    "message": "Execution failed for MCP tool 'resolve-library-id': MCP error -32602: MCP error -32602: Invalid arguments for tool resolve-library-id: [\n  {\n    \"code\": \"invalid_type\",\n    \"expected\": \"string\",\n    \"received\": \"undefined\",\n    \"path\": [\n      \"libraryName\"\n    ],\n    \"message\": \"Required\"\n  }\n]"
  },
  "result": ""
}

𝌚 CopilotKit Version

"@copilotkit/react-core": "^1.8.13",
 "@copilotkit/react-ui": "^1.8.13",

📄 Logs (Optional)


koikar avatar Jun 05 '25 11:06 koikar

Thank you for bringing this to our attention. We'll look into this. If you need immediate assistance, please reserve a slot here: https://cal.com/nathan-tarbert-copilotkit/15min

copilotkit-support avatar Jun 06 '25 05:06 copilotkit-support

The reason for this error is at line https://github.com/CopilotKit/CopilotKit/blob/dd6e9e57bb94492795c5cc41c5cbd164e3d1a724/CopilotKit/packages/runtime/src/lib/runtime/mcp-tools-utils.ts#L98

It should be this instead

const result = await tool.execute({ ...params });

Because the MCP endpoints received the text wrapped in a params object, where it should be flat.

lostfields avatar Jun 18 '25 13:06 lostfields

I also meet this issue. I wrote an MCP server using FastMCP, the code like the following:

import dotenv from "dotenv";
import { FastMCP } from "fastmcp";
import { z } from "zod";
dotenv.config();

const  mcpServer=new FastMCP({
    name: "mcp-server",
    version: "1.0.0",
});

mcpServer.addTool({
    name: "add",
    description: "Add two numbers",
    parameters: z.object({
      a: z.number(),
      b: z.number(),
    }),
    execute: async (args) => {
      return String(args.a + args.b);
    },
  });

async function main() {
    await mcpServer.start({
        transportType:"httpStream", 
        httpStream:{
            port:3000,
        }
    });
}
main();

And use the following code to call the MCP server:

  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
  import { experimental_createMCPClient as excreateMCPClient } from "ai"

  const runtime = new CopilotRuntime({
    systemPrompt: `
    You are an intelligent assistant. When the user inputs an addition expression (such as "1+2" or "add 3 and 5"), please parse it into { "a": 1, "b": 2 } and call the correct tool.
    `,
    mcpServers: [{endpoint: "http://localhost:3000/mcp",}],
    createMCPClient: async (config) => {
      console.log("Connect to:", config.endpoint);
      
      return await excreateMCPClient({
          transport: new StreamableHTTPClientTransport(new URL(config.endpoint),
      ),
      });
    },
  });

And the error is: Error in action handler [Error: Execution failed for MCP tool 'add': MCP error -32602: Tool 'add' parameter validation failed: a: Required, b: Required. Please check the parameter types and values according to the tool's schema.]

huweihong avatar Jul 09 '25 13:07 huweihong

The reason for this error is at line

CopilotKit/CopilotKit/packages/runtime/src/lib/runtime/mcp-tools-utils.ts

Line 98 in dd6e9e5 const result = await tool.execute({ params });

It should be this instead

const result = await tool.execute({ ...params });

Because the MCP endpoints received the text wrapped in a params object, where it should be flat.

This proposed change was made here https://github.com/CopilotKit/CopilotKit/pull/2100 so it should be fixed in v1.9.3

hejtmii avatar Jul 23 '25 11:07 hejtmii

Hello @hejtmii I still have issues with params not being populated on tool calls. I did reproduce running the Mcp tutorial https://docs.copilotkit.ai/direct-to-llm/guides/model-context-protocol?cli=use-cli and I have checked the version which is "@copilotkit/react-core": "^1.9.3", "@copilotkit/react-ui": "^1.9.3", Was the fix included in 1.9.3 ?

alankpax avatar Jul 31 '25 19:07 alankpax

Hi, is there any update on that issue? I'm facing it also on copilotkit/[email protected]. The runtime correctly reads my MCP tools, but when calling one of them, the parameters are not passed.

marekgoczol avatar Aug 10 '25 10:08 marekgoczol

You can debug MCP Server tool call parameter errors in CopilotKit Cloud runtime by enabling the developer console, setting up error handlers, and configuring runtime logging. These approaches provide detailed error messages and technical details to help diagnose issues with parameter passing and validation.

Development Debugging (Immediate Setup)

Enable Developer Console (No API key required):

import { CopilotKit } from "@copilotkit/react-core";

<CopilotKit 
  runtimeUrl="/api/copilotkit"
  showDevConsole={true}  // Shows detailed errors in browser
>
  {/* Your app */}
</CopilotKit>

Console Logging for MCP Errors - The runtime automatically logs MCP tool errors:

Error executing MCP tool '{toolName}' from endpoint {mcpEndpoint}:
Execution failed for MCP tool '{toolName}': {error.message}

Production Error Debugging

Setup Error Handler (Requires publicLicenseKey):

import { CopilotKit } from "@copilotkit/react-core";

<CopilotKit 
  runtimeUrl="/api/copilotkit"
  publicApiKey="your-public-api-key"
  onError={(error) => {
    console.error('CopilotKit Error:', {
      source: error.source,        // 'ui', 'runtime', or 'agent'
      type: error.type,           // 'error', 'action', 'request', etc.
      request: error.request,     // Request data
      response: error.response,   // Response data
      technicalDetails: error.technicalDetails
    });
    
    // Send to monitoring service
    // Sentry.captureException(error);
  }}
>
  {/* Your app */}
</CopilotKit>

Runtime-Side Debugging

Configure Runtime Logging (Environment variable):

# Set log level for detailed MCP debugging
LOG_LEVEL=debug  # Options: debug, info, warn, error

MCP-Specific Debug Information - MCP tools include debug metadata:

  • _isMCPTool: true - Identifies MCP tools in logs
  • _mcpEndpoint: mcpEndpoint - Shows which MCP server is being called

Parameter Validation Debugging Steps

Check MCP Server Configuration:

// Verify MCP servers are properly configured
const { setMcpServers } = useCopilotChat();

setMcpServers([{
  endpoint: "your-mcp-server-endpoint",
  apiKey: "your-api-key"  // Optional
}]);

Parameter Schema Validation - The runtime uses extractParametersFromSchema for parameter validation. Common issues:

  • Missing required parameters
  • Type mismatches (expected string, received undefined)
  • Invalid parameter schemas from MCP server

Check Runtime Error Logs - Look for these error patterns:

  • HANDLER_ERROR - General action execution error
  • invalid_type - Parameter type validation failure
  • CopilotKitMisuseError - Configuration issues (e.g., MCP servers without createMCPClient)

Advanced Debugging Techniques

Custom Error Analytics Integration:

onError={(error) => {
  // Custom analytics
  analytics.track('CopilotKit Error', {
    errorType: error.type,
    source: error.source,
    mcpEndpoint: error.technicalDetails?.mcpEndpoint,
    toolName: error.technicalDetails?.toolName
  });
}}

Network Request Debugging - Monitor API calls between Next.js app and MCP Server:

  • Check browser DevTools Network tab
  • Verify request/response payloads
  • Confirm parameter serialization

Troubleshooting Common Issues

Parameter Not Passed: Check if parameters are correctly defined in your Next.js action handlers • Type Mismatch: Verify MCP server expects the correct parameter types • Missing MCP Server: Ensure MCP server is running and accessible from Cloud runtime • Configuration Error: Verify createMCPClient is properly set up when using MCP servers

Documentation References:

Note: The showDevConsole approach provides immediate visibility during development, while the onError handler with publicApiKey offers comprehensive production debugging capabilities.


Was this helpful?

If this solution worked for you, please click on the appropriate option below to help us improve:

✅ Issue Solved | ❌ Need more help

👋 Thanks for your feedback!

I've escalated this issue to our development team. Someone from our team will review your request and provide additional assistance shortly.

If this is blocking production, please book a meeting with us at https://cal.com/nathan-tarbert-copilotkit/15min