#How to automatically adjust the MCP Key based on the currently logged-in user?

1 messages · Page 1 of 1 (latest)

acoustic rain
#

How to automatically adjust the MCP Key based on the currently logged-in user?

sudden sentinelBOT
#

This solution has been AI generated

You can set the MCP key per logged-in user either on the client (by updating the provider’s mcpServers with the user’s key) or on the server (by looking it up and instantiating the runtime per request). The backend-driven approach is recommended for security since the key never reaches the browser.

Frontend (dynamic per user)

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

function App() {
  const { user } = useAuth();
  return (
    <CopilotKit
      runtimeUrl="/api/copilotkit"
      properties={{
        mcpServers: [
          { endpoint: "https://mcp.your-server.com/sse", apiKey: user?.mcpApiKey }
        ]
      }}
    >
      <YourApp />
    </CopilotKit>
  );
}

Or update after login:

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

function McpKeyManager({ userMcpKey }: { userMcpKey?: string }) {
  const { setMcpServers } = useCopilotKit();
  useEffect(() => {
    if (userMcpKey) {
      setMcpServers([{ endpoint: "https://mcp.your-server.com/sse", apiKey: userMcpKey }]);
    }
  }, [userMcpKey, setMcpServers]);
  return null;
}

Backend (secure; per-request runtime)

// app/api/copilotkit/route.ts
import { NextRequest } from "next/server";
import { CopilotRuntime, OpenAIAdapter, copilotRuntimeNextJSAppRouterEndpoint } from "@copilotkit/runtime";

export const POST = async (req: NextRequest) => {
  const userId = req.headers.get("x-user-id");
  const userMcpKey = await db.mcpKeys.findUnique({ where: { userId } });

  const runtime = new CopilotRuntime({
    mcpServers: [{ endpoint: "https://mcp.your-server.com/sse", apiKey: userMcpKey }],
    async createMCPClient(cfg) {
      return experimental_createMCPClient({
        transport: { type: "sse", url: cfg.endpoint, headers: cfg.apiKey ? { Authorization: `Bearer ${cfg.apiKey}` } : undefined }
      });
    }
  });

#
  const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
    runtime,
    serviceAdapter: new OpenAIAdapter(),
    endpoint: "/api/copilotkit",
  });
  return handleRequest(req);
};

Notes

  • Pass keys via provider properties (mcpServers) or keep them server-side for stronger security.
  • Ensure SSE transport and matching endpoint paths when creating the MCP client.

Was this helpful?

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

sudden sentinelBOT
#

Thank you for your feedback! Our team will provide additional assistance. 🔄

acoustic rain
#

can give a demo?

sudden sentinelBOT