Skip to content

🚀 Feature Request: Support MCP servers with dynamic API keys #2407

Closed

Description

@hejtmii

🎤 Tell us your idea

We have a central MCP server serving multiple users

The server passes given API key (authentication token) to the underlying Management API which uses the API key to evaluate permissions

We are using a single instance of self-hosted runtime of CopilotKit with createMCPClient configured

MCP server is defined at the FE (via setMcpServers), passing the server URL + API key of the given user

Every user has their own authentication tokens that are automatically provided and refreshed by the UI code
Tokens are short living (max 10 minutes)
One user may have more tokens (each browser window has its own)

The problem is that CopilotKit assumes that the configuration of MCP server is static during the run of the app, having a static API key

The underlying action cache is only indexed by endpointUrl, API key not included at all

let actionsForEndpoint: Action<any>[] | undefined = this.mcpActionCache.get(endpointUrl);

We bypass that by appending unique query parameter to the endpointUrl ... ?uid={hash_of_api_key} so that they are cached for every API key separately. It somewhat works, BUT...

  • It causes a memory leak, keeping all no longer MCP clients in the memory - There is no way to clear the cache / it has no timeout for the entries
  • Every newly setup endpointUrl must initialize its available tools (which further extends the memory leak footprint), even though the server is the same

There should be some way to handle this situation, being able to have a single endpointUrl of a shared server instance, passing the API key from the individual request to the tool call.

It might be enough if the MCP tool call got the respective context (related MCP server config) in its second parameter. The custom MCP client could then extract it and add the API key dynamically to the request headers for that specific call.

Please add such feature, or advise how it could be done with the current code.

Activity

  1. added
    feature request
    on Sep 2, 2025
  2. copilotkit-support-bot commented on Sep 2, 2025

    @copilotkit-support-bot

    CopilotKit currently assumes a static MCP server configuration, which makes dynamic API key management challenging. However, there are ways to work around this and suggestions for more robust solutions.

    Details

    Current MCP Implementation Limitations

    • The MCPServerConfig interface only supports static API keys: { endpoint: string; apiKey?: string }
    • API keys are configured once during CopilotRuntime initialization
    • Actions are cached by endpoint URL only, not by user/session context
    • There are no built-in cache invalidation methods for expired API keys

    Existing Dynamic Capabilities

    • The getServerSideActions() method can merge base endpoints with request-specific endpoints per request
    • The frontend useCopilotChat hook supports dynamic MCP server updates via setMcpServers
    • Request-specific endpoints passed via graphqlContext.properties.mcpServers override the base configuration
    • The MCPClient interface allows for custom implementations that could handle dynamic authentication
    • Request context infrastructure exists to carry user-specific data

    Recommended Implementation Approaches

    Approach 1: Dynamic MCP Server Configuration (Frontend-driven)

    // In your React component
    const { setMcpServers } = useCopilotChat();
    
    // Update MCP servers with user-specific API keys
    const updateUserMCPServers = (userId: string, apiKey: string) => {
      setMcpServers([
        {
          endpoint: "your-mcp-endpoint",
          apiKey: apiKey // Dynamic API key per user
        }
      ]);
    };
    
    // Call when user authenticates or API key changes
    useEffect(() => {
      updateUserMCPServers(currentUser.id, currentUser.mcpApiKey);
    }, [currentUser]);

    Approach 2: Request Context Enhancement (Backend-driven)

    // Extend the runtime with user context
    class CustomCopilotRuntime extends CopilotRuntime {
      async getServerSideActions(graphqlContext: any) {
        // Extract user context from headers/auth
        const userId = graphqlContext.req.headers['x-user-id'];
        const userApiKey = await getUserMCPApiKey(userId);
        
        // Create user-specific MCP servers
        const userMcpServers = [{
          endpoint: "your-mcp-endpoint",
          apiKey: userApiKey
        }];
        
        // Override request MCP servers
        graphqlContext.properties = {
          ...graphqlContext.properties,
          mcpServers: userMcpServers
        };
        
        return super.getServerSideActions(graphqlContext);
      }
    }

    Approach 3: Custom MCP Client with Dynamic Auth

    // Create a custom MCP client that handles dynamic auth
    class DynamicAuthMCPClient implements MCPClient {
      constructor(private getUserApiKey: (userId: string) => Promise<string>) {}
      
      async listTools(endpoint: string, context?: any): Promise<any[]> {
        const userId = context?.userId;
        const apiKey = await this.getUserApiKey(userId);
        
        // Make request with dynamic API key
        return this.makeRequest(endpoint, { apiKey });
      }
      
      async callTool(endpoint: string, toolName: string, args: any, context?: any): Promise<any> {
        const userId = context?.userId;
        const apiKey = await this.getUserApiKey(userId);
        
        // Make tool call with dynamic API key  
        return this.makeRequest(endpoint, { apiKey, toolName, args });
      }
    }

    Cache Management Solutions

    User-Specific Cache Keys

    // Modify cache keys to include user context
    const getCacheKey = (endpoint: string, userId: string) => `${endpoint}:${userId}`;
    
    // Clear user-specific cache when API key expires
    const clearUserMCPCache = (userId: string) => {
      for (const [key] of mcpActionCache.entries()) {
        if (key.endsWith(`:${userId}`)) {
          mcpActionCache.delete(key);
        }
      }
    };

    Time-Based Cache Invalidation

    // Add TTL to cached actions
    interface CachedMCPAction {
      actions: any[];
      timestamp: number;
      ttl: number;
    }
    
    const isCacheValid = (cached: CachedMCPAction) => {
      return Date.now() - cached.timestamp < cached.ttl;
    };

    Implementation Priority

    • Immediate Solution: Use frontend setMcpServers with user-specific API keys and update MCP configuration when user auth state changes.
    • Long-term Solution: Extend runtime with custom user context handling, implement user-specific caching with proper invalidation, and create a custom MCP client for advanced dynamic auth scenarios.

    Documentation References:

    Source Code References:

    The frontend-driven approach provides the quickest path to dynamic API key support, while backend and custom client approaches offer more robust, scalable solutions.


    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

  3. copilotkit-support-bot commented on Sep 2, 2025

    @copilotkit-support-bot

    👋 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

  4. BenTaylorDev commented on Sep 6, 2026

    @BenTaylorDev
    Contributor

    An update after digging into this properly, @hejtmii — with one piece of bad news and one genuinely good one.

    The bad news. Your reading of the cache was right, and it goes further than you found. On the v1 CopilotRuntime, mcpServers endpoints are deduped by URL alone, the tool cache is keyed by endpoint alone with no TTL and no eviction, and the MCP client is never closed. But underneath all of that, v1 MCP tools are built with execute: () => Promise.resolve() — so the tools are advertised to the model and then never actually called. The ?uid={hash} workaround you built was paying a memory cost for a path that could not have executed. Two more defects in the same method: mcpServers is ignored entirely unless you also pass actions, and the request-scoped merge that would carry the frontend's setMcpServers never runs, because its only call site passes no arguments. All of that is now tracked in #6408, and the support-bot answer above ("Approach 1: frontend-driven setMcpServers") does not work for that reason — sorry for the year of it standing unchallenged.

    The good news: v2 already does what you asked for here. Not as a cache-key change, but by removing the cache. The v2 runtime accepts a factory that runs per request and receives the raw Request:

    import { CopilotRuntime, BuiltInAgent } from "@copilotkit/runtime/v2";
    
    const runtime = new CopilotRuntime({
      agents: ({ request }) => {
        const apiKey = request.headers.get("authorization");
        return {
          default: new BuiltInAgent({
            model: "openai/gpt-4o",
            mcpServers: [{
              type: "http",
              url: "https://your-mcp-server",
              options: { requestInit: { headers: { Authorization: apiKey } } },
            }],
          }),
        };
      },
    });

    One shared endpointUrl, a different key per request, and no hash-in-the-URL trick. The MCP client is created for that run and closed when the run ends, so there is nothing to leak and nothing to evict. If you would rather own the connections yourself — persistent sockets, your own tool caching, your own refresh — pass mcpClients instead of mcpServers and the agent will only call .tools() on them: see MCP servers, which calls out dynamic auth as the reason to prefer that.

    The one thing v2 does not give you is re-listing avoidance across runs, since mcpServers reconnects each run. mcpClients is the answer there.

    Leaving this open: what to do with the v1 parameters is part of #6408.

  5. BenTaylorDev commented on Sep 6, 2026

    @BenTaylorDev
    Contributor

    Correcting my snippet above: for type: "http" I wrote options: { requestInit: { headers } }, which is not the shape this codebase recommends. MCPClientConfigHTTP.options is typed as StreamableHTTPClientTransportOptions, and its own JSDoc in packages/runtime/src/agent/index.ts says the documented extension point for per-request customization is options.fetch — pass a wrapped fetch when you need dynamic headers:

    agents: ({ request }) => {
      const auth = request.headers.get("authorization") ?? "";
      return {
        default: new BuiltInAgent({
          model: "openai/gpt-4o",
          mcpServers: [{
            type: "http",
            url: "https://your-mcp-server",
            options: {
              fetch: (url, init) =>
                fetch(url, { ...init, headers: { ...init?.headers, Authorization: auth } }),
            },
          }],
        }),
      };
    }

    The per-request point stands unchanged: the factory runs per request, so the token is whatever that caller sent, and the client is closed when the run ends.

  6. BenTaylorDev commented on Sep 15, 2026

    @BenTaylorDev
    Contributor

    Status update, because the ground under this request moved with #6931 (merged 2026-09-15, not yet released).

    The v1 MCP path executes again. getToolsFromMCP was dropping tool.execute and substituting a no-op, so no v1 MCP tool ran at all. That is fixed, and mcpServers is now attached independently of actions, so an MCP-only runtime receives its tools. An endpoint that fails its first connection also retries instead of caching an empty tool list for the life of the runtime.

    This request is still not repaired. The client cache is still keyed by endpointUrl alone, so two users with different credentials share one client, and MCPClient.close?() is still never called. Your ?uid=<hash> workaround still leaks a client per key.

    The reason is now written down: #7116. The v1 CopilotRuntime resolves its agents once and bakes the resulting tools onto the agent instances, so it cannot use the per-request agent factory the v2 runtime has had since #2941. Per-request credential keying needs that to change first. Keeping this open and tracking it there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions