Repository navigation
Description
🎤 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
endpointUrlmust 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
linear commentedon Sep 2, 2025
CPK-4490 🚀 Feature Request: Support MCP servers with dynamic API keys
copilotkit-support-bot commentedon Sep 2, 2025
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
MCPServerConfiginterface only supports static API keys:{ endpoint: string; apiKey?: string }CopilotRuntimeinitializationExisting Dynamic Capabilities
getServerSideActions()method can merge base endpoints with request-specific endpoints per requestuseCopilotChathook supports dynamic MCP server updates viasetMcpServersgraphqlContext.properties.mcpServersoverride the base configurationMCPClientinterface allows for custom implementations that could handle dynamic authenticationRecommended Implementation Approaches
Approach 1: Dynamic MCP Server Configuration (Frontend-driven)
Approach 2: Request Context Enhancement (Backend-driven)
Approach 3: Custom MCP Client with Dynamic Auth
Cache Management Solutions
User-Specific Cache Keys
Time-Based Cache Invalidation
Implementation Priority
setMcpServerswith user-specific API keys and update MCP configuration when user auth state changes.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
copilotkit-support-bot commentedon Sep 2, 2025
👋 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
BenTaylorDev commentedon Sep 6, 2026
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,mcpServersendpoints are deduped by URL alone, the tool cache is keyed byendpointalone with no TTL and no eviction, and the MCP client is never closed. But underneath all of that, v1 MCP tools are built withexecute: () => 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:mcpServersis ignored entirely unless you also passactions, and the request-scoped merge that would carry the frontend'ssetMcpServersnever 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-drivensetMcpServers") 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: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 — passmcpClientsinstead ofmcpServersand 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
mcpServersreconnects each run.mcpClientsis the answer there.Leaving this open: what to do with the v1 parameters is part of #6408.
BenTaylorDev commentedon Sep 6, 2026
Correcting my snippet above: for
type: "http"I wroteoptions: { requestInit: { headers } }, which is not the shape this codebase recommends.MCPClientConfigHTTP.optionsis typed asStreamableHTTPClientTransportOptions, and its own JSDoc inpackages/runtime/src/agent/index.tssays the documented extension point for per-request customization isoptions.fetch— pass a wrapped fetch when you need dynamic headers: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.
fix: repair the v1.50.0 orphans that fail silently (MCP auth, adapter…
fix(runtime): reject v1 `actions` and `mcpServers` instead of breakin…
docs: stop teaching v1 MCP and CopilotTextarea as working paths
BenTaylorDev commentedon Sep 15, 2026
Status update, because the ground under this request moved with #6931 (merged 2026-09-15, not yet released).
The v1 MCP path executes again.
getToolsFromMCPwas droppingtool.executeand substituting a no-op, so no v1 MCP tool ran at all. That is fixed, andmcpServersis now attached independently ofactions, 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
endpointUrlalone, so two users with different credentials share one client, andMCPClient.close?()is still never called. Your?uid=<hash>workaround still leaks a client per key.The reason is now written down: #7116. The v1
CopilotRuntimeresolves 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.fix(runtime): resolve v1 agents per request so actions and MCP see th…
fix(runtime): keep MCP credentials out of the log and evict only the …
fix(runtime): redact the endpoint everywhere it leaves the process, n…
fix: keep MCP URL credentials out of logs and validate MCP Apps CSP d…