@chat-js/registry 0.1.2 → 0.2.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -8
- package/dist/r/ai-titles.json +50 -0
- package/dist/r/akamai-storage.json +44 -0
- package/dist/r/alibaba-storage.json +44 -0
- package/dist/r/appwrite-storage.json +50 -0
- package/dist/r/archil-storage.json +52 -0
- package/dist/r/attachment-uploads.json +90 -0
- package/dist/r/azure-storage.json +51 -0
- package/dist/r/backblaze-b2-storage.json +44 -0
- package/dist/r/base/ai-titles.json +50 -0
- package/dist/r/base/akamai-storage.json +44 -0
- package/dist/r/base/alibaba-storage.json +44 -0
- package/dist/r/base/appwrite-storage.json +50 -0
- package/dist/r/base/archil-storage.json +52 -0
- package/dist/r/base/attachment-uploads.json +90 -0
- package/dist/r/base/azure-storage.json +51 -0
- package/dist/r/base/backblaze-b2-storage.json +44 -0
- package/dist/r/base/bunny-storage-storage.json +48 -0
- package/dist/r/base/cloudinary-storage.json +43 -0
- package/dist/r/base/code-documents.json +96 -0
- package/dist/r/base/code-execution-runtime.json +25 -0
- package/dist/r/base/code-execution-ui.json +32 -0
- package/dist/r/base/code-execution.json +69 -0
- package/dist/r/base/credits.json +103 -0
- package/dist/r/base/daytona-sandbox.json +55 -0
- package/dist/r/base/deep-research.json +224 -0
- package/dist/r/base/delete-document.json +58 -0
- package/dist/r/base/digitalocean-spaces-storage.json +44 -0
- package/dist/r/base/dropbox-storage.json +43 -0
- package/dist/r/base/exoscale-storage.json +44 -0
- package/dist/r/base/feedback.json +112 -0
- package/dist/r/base/filebase-storage.json +43 -0
- package/dist/r/base/firebase-storage-storage.json +52 -0
- package/dist/r/base/firecrawl-search.json +72 -0
- package/dist/r/base/followup-suggestions.json +152 -0
- package/dist/r/base/ftp-storage.json +54 -0
- package/dist/r/base/gcs-storage.json +33 -0
- package/dist/r/base/generate-image.json +101 -0
- package/dist/r/base/generate-video.json +70 -0
- package/dist/r/base/get-weather.json +52 -0
- package/dist/r/base/google-drive-storage.json +47 -0
- package/dist/r/base/hetzner-storage.json +44 -0
- package/dist/r/base/ibm-cos-storage.json +44 -0
- package/dist/r/base/idrive-e2-storage.json +44 -0
- package/dist/r/base/langfuse.json +63 -0
- package/dist/r/base/litellm-gateway.json +67 -0
- package/dist/r/base/mcp.json +320 -0
- package/dist/r/base/memory-storage.json +28 -0
- package/dist/r/base/minio-storage.json +44 -0
- package/dist/r/base/model-preferences.json +131 -0
- package/dist/r/base/neon-storage.json +44 -0
- package/dist/r/base/netlify-blobs-storage.json +31 -0
- package/dist/r/base/onedrive-storage.json +48 -0
- package/dist/r/base/openai-compatible-gateway.json +69 -0
- package/dist/r/base/openai-gateway.json +67 -0
- package/dist/r/base/openrouter-gateway.json +75 -0
- package/dist/r/base/oracle-cloud-storage.json +45 -0
- package/dist/r/base/ovhcloud-storage.json +44 -0
- package/dist/r/base/pocketbase-storage.json +50 -0
- package/dist/r/base/projects.json +275 -0
- package/dist/r/base/r2-storage.json +44 -0
- package/dist/r/base/read-document.json +34 -0
- package/dist/r/base/registry.json +4949 -0
- package/dist/r/base/retrieve-url.json +69 -0
- package/dist/r/base/s3-storage.json +44 -0
- package/dist/r/base/saved-code-execution.json +84 -0
- package/dist/r/base/scaleway-storage.json +44 -0
- package/dist/r/base/search.json +146 -0
- package/dist/r/base/sftp-storage.json +58 -0
- package/dist/r/base/sharepoint-storage.json +50 -0
- package/dist/r/base/sharing.json +144 -0
- package/dist/r/base/sheet-documents.json +94 -0
- package/dist/r/base/storj-storage.json +43 -0
- package/dist/r/base/supabase-storage.json +48 -0
- package/dist/r/base/tavily-search.json +72 -0
- package/dist/r/base/tencent-storage.json +44 -0
- package/dist/r/base/text-documents.json +117 -0
- package/dist/r/base/tigris-storage.json +43 -0
- package/dist/r/base/uploadthing-storage.json +38 -0
- package/dist/r/base/vercel-analytics.json +46 -0
- package/dist/r/base/vercel-blob-storage.json +42 -0
- package/dist/r/base/vercel-gateway.json +77 -0
- package/dist/r/base/vercel-sandbox.json +67 -0
- package/dist/r/base/vercel-speed-insights.json +46 -0
- package/dist/r/base/vultr-storage.json +44 -0
- package/dist/r/base/wasabi-storage.json +44 -0
- package/dist/r/base/webdav-storage.json +52 -0
- package/dist/r/base/word-count.json +51 -0
- package/dist/r/base/yandex-storage.json +43 -0
- package/dist/r/bunny-storage-storage.json +48 -0
- package/dist/r/cloudinary-storage.json +43 -0
- package/dist/r/code-documents.json +96 -0
- package/dist/r/code-execution-runtime.json +25 -0
- package/dist/r/code-execution-ui.json +32 -0
- package/dist/r/code-execution.json +69 -0
- package/dist/r/credits.json +103 -0
- package/dist/r/daytona-sandbox.json +55 -0
- package/dist/r/deep-research.json +224 -0
- package/dist/r/delete-document.json +58 -0
- package/dist/r/digitalocean-spaces-storage.json +44 -0
- package/dist/r/dropbox-storage.json +43 -0
- package/dist/r/exoscale-storage.json +44 -0
- package/dist/r/feedback.json +112 -0
- package/dist/r/filebase-storage.json +43 -0
- package/dist/r/firebase-storage-storage.json +52 -0
- package/dist/r/firecrawl-search.json +72 -0
- package/dist/r/followup-suggestions.json +152 -0
- package/dist/r/ftp-storage.json +54 -0
- package/dist/r/gcs-storage.json +33 -0
- package/dist/r/generate-image.json +101 -0
- package/dist/r/generate-video.json +70 -0
- package/dist/r/get-weather.json +52 -0
- package/dist/r/google-drive-storage.json +47 -0
- package/dist/r/hetzner-storage.json +44 -0
- package/dist/r/ibm-cos-storage.json +44 -0
- package/dist/r/idrive-e2-storage.json +44 -0
- package/dist/r/langfuse.json +63 -0
- package/dist/r/litellm-gateway.json +67 -0
- package/dist/r/mcp.json +320 -0
- package/dist/r/memory-storage.json +28 -0
- package/dist/r/minio-storage.json +44 -0
- package/dist/r/model-preferences.json +131 -0
- package/dist/r/neon-storage.json +44 -0
- package/dist/r/netlify-blobs-storage.json +31 -0
- package/dist/r/onedrive-storage.json +48 -0
- package/dist/r/openai-compatible-gateway.json +69 -0
- package/dist/r/openai-gateway.json +67 -0
- package/dist/r/openrouter-gateway.json +75 -0
- package/dist/r/oracle-cloud-storage.json +45 -0
- package/dist/r/ovhcloud-storage.json +44 -0
- package/dist/r/pocketbase-storage.json +50 -0
- package/dist/r/projects.json +275 -0
- package/dist/r/r2-storage.json +44 -0
- package/dist/r/radix/ai-titles.json +50 -0
- package/dist/r/radix/akamai-storage.json +44 -0
- package/dist/r/radix/alibaba-storage.json +44 -0
- package/dist/r/radix/appwrite-storage.json +50 -0
- package/dist/r/radix/archil-storage.json +52 -0
- package/dist/r/radix/attachment-uploads.json +90 -0
- package/dist/r/radix/azure-storage.json +51 -0
- package/dist/r/radix/backblaze-b2-storage.json +44 -0
- package/dist/r/radix/bunny-storage-storage.json +48 -0
- package/dist/r/radix/cloudinary-storage.json +43 -0
- package/dist/r/radix/code-documents.json +96 -0
- package/dist/r/radix/code-execution-runtime.json +25 -0
- package/dist/r/radix/code-execution-ui.json +32 -0
- package/dist/r/radix/code-execution.json +69 -0
- package/dist/r/radix/credits.json +103 -0
- package/dist/r/radix/daytona-sandbox.json +55 -0
- package/dist/r/radix/deep-research.json +224 -0
- package/dist/r/radix/delete-document.json +58 -0
- package/dist/r/radix/digitalocean-spaces-storage.json +44 -0
- package/dist/r/radix/dropbox-storage.json +43 -0
- package/dist/r/radix/exoscale-storage.json +44 -0
- package/dist/r/radix/feedback.json +112 -0
- package/dist/r/radix/filebase-storage.json +43 -0
- package/dist/r/radix/firebase-storage-storage.json +52 -0
- package/dist/r/radix/firecrawl-search.json +72 -0
- package/dist/r/radix/followup-suggestions.json +152 -0
- package/dist/r/radix/ftp-storage.json +54 -0
- package/dist/r/radix/gcs-storage.json +33 -0
- package/dist/r/radix/generate-image.json +101 -0
- package/dist/r/radix/generate-video.json +70 -0
- package/dist/r/radix/get-weather.json +52 -0
- package/dist/r/radix/google-drive-storage.json +47 -0
- package/dist/r/radix/hetzner-storage.json +44 -0
- package/dist/r/radix/ibm-cos-storage.json +44 -0
- package/dist/r/radix/idrive-e2-storage.json +44 -0
- package/dist/r/radix/langfuse.json +63 -0
- package/dist/r/radix/litellm-gateway.json +67 -0
- package/dist/r/radix/mcp.json +320 -0
- package/dist/r/radix/memory-storage.json +28 -0
- package/dist/r/radix/minio-storage.json +44 -0
- package/dist/r/radix/model-preferences.json +131 -0
- package/dist/r/radix/neon-storage.json +44 -0
- package/dist/r/radix/netlify-blobs-storage.json +31 -0
- package/dist/r/radix/onedrive-storage.json +48 -0
- package/dist/r/radix/openai-compatible-gateway.json +69 -0
- package/dist/r/radix/openai-gateway.json +67 -0
- package/dist/r/radix/openrouter-gateway.json +75 -0
- package/dist/r/radix/oracle-cloud-storage.json +45 -0
- package/dist/r/radix/ovhcloud-storage.json +44 -0
- package/dist/r/radix/pocketbase-storage.json +50 -0
- package/dist/r/radix/projects.json +275 -0
- package/dist/r/radix/r2-storage.json +44 -0
- package/dist/r/radix/read-document.json +34 -0
- package/dist/r/radix/registry.json +4949 -0
- package/dist/r/radix/retrieve-url.json +69 -0
- package/dist/r/radix/s3-storage.json +44 -0
- package/dist/r/radix/saved-code-execution.json +84 -0
- package/dist/r/radix/scaleway-storage.json +44 -0
- package/dist/r/radix/search.json +146 -0
- package/dist/r/radix/sftp-storage.json +58 -0
- package/dist/r/radix/sharepoint-storage.json +50 -0
- package/dist/r/radix/sharing.json +144 -0
- package/dist/r/radix/sheet-documents.json +94 -0
- package/dist/r/radix/storj-storage.json +43 -0
- package/dist/r/radix/supabase-storage.json +48 -0
- package/dist/r/radix/tavily-search.json +72 -0
- package/dist/r/radix/tencent-storage.json +44 -0
- package/dist/r/radix/text-documents.json +117 -0
- package/dist/r/radix/tigris-storage.json +43 -0
- package/dist/r/radix/uploadthing-storage.json +38 -0
- package/dist/r/radix/vercel-analytics.json +46 -0
- package/dist/r/radix/vercel-blob-storage.json +42 -0
- package/dist/r/radix/vercel-gateway.json +77 -0
- package/dist/r/radix/vercel-sandbox.json +67 -0
- package/dist/r/radix/vercel-speed-insights.json +46 -0
- package/dist/r/radix/vultr-storage.json +44 -0
- package/dist/r/radix/wasabi-storage.json +44 -0
- package/dist/r/radix/webdav-storage.json +52 -0
- package/dist/r/radix/word-count.json +51 -0
- package/dist/r/radix/yandex-storage.json +43 -0
- package/dist/r/read-document.json +34 -0
- package/dist/r/registry.json +4949 -0
- package/dist/r/retrieve-url.json +69 -0
- package/dist/r/s3-storage.json +44 -0
- package/dist/r/saved-code-execution.json +84 -0
- package/dist/r/scaleway-storage.json +44 -0
- package/dist/r/search.json +146 -0
- package/dist/r/sftp-storage.json +58 -0
- package/dist/r/sharepoint-storage.json +50 -0
- package/dist/r/sharing.json +144 -0
- package/dist/r/sheet-documents.json +94 -0
- package/dist/r/storj-storage.json +43 -0
- package/dist/r/supabase-storage.json +48 -0
- package/dist/r/tavily-search.json +72 -0
- package/dist/r/tencent-storage.json +44 -0
- package/dist/r/text-documents.json +117 -0
- package/dist/r/tigris-storage.json +43 -0
- package/dist/r/uploadthing-storage.json +38 -0
- package/dist/r/vercel-analytics.json +46 -0
- package/dist/r/vercel-blob-storage.json +42 -0
- package/dist/r/vercel-gateway.json +77 -0
- package/dist/r/vercel-sandbox.json +67 -0
- package/dist/r/vercel-speed-insights.json +46 -0
- package/dist/r/vultr-storage.json +44 -0
- package/dist/r/wasabi-storage.json +44 -0
- package/dist/r/webdav-storage.json +52 -0
- package/dist/r/word-count.json +51 -0
- package/dist/r/yandex-storage.json +43 -0
- package/package.json +113 -31
- package/index.d.ts +0 -4
- package/index.js +0 -1
- package/index.json +0 -19
- package/items/get-weather.json +0 -26
- package/items/retrieve-url.json +0 -35
- package/items/toolkit-renderer.json +0 -29
- package/items/word-count.json +0 -22
package/dist/r/mcp.json
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "mcp",
|
|
4
|
+
"description": "MCP connectors, management pages, OAuth and composer control",
|
|
5
|
+
"dependencies": [
|
|
6
|
+
"@ai-sdk/mcp@2.0.73",
|
|
7
|
+
"@hookform/resolvers@^5.2.1",
|
|
8
|
+
"@modelcontextprotocol/sdk@^1.24.3",
|
|
9
|
+
"@tanstack/react-query@^5.104.1",
|
|
10
|
+
"@trpc/server@^11.1.2",
|
|
11
|
+
"ajv@8.18.0",
|
|
12
|
+
"drizzle-orm@^0.45.1",
|
|
13
|
+
"guarded-fetch@^0.1.4",
|
|
14
|
+
"lucide-react@0.553.0",
|
|
15
|
+
"nuqs@^2.8.5",
|
|
16
|
+
"postgres@^3.4.4",
|
|
17
|
+
"react-hook-form@^7.62.0",
|
|
18
|
+
"sonner@^2.0.7",
|
|
19
|
+
"superjson@^2.2.2"
|
|
20
|
+
],
|
|
21
|
+
"files": [
|
|
22
|
+
{
|
|
23
|
+
"path": "src/plugins/mcp/adapters/agent/tools/mcp.ts",
|
|
24
|
+
"content": "export { mcpTools as default } from \"@/plugins/mcp/runtime/agent-tools\";\n",
|
|
25
|
+
"type": "registry:file",
|
|
26
|
+
"target": "~/agent/tools/mcp.ts"
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
"path": "src/plugins/mcp/src/runtime/agent-tools.ts",
|
|
30
|
+
"content": "import { isGuestSession } from \"@/lib/eve/session-identity\";\nimport type { ToolDefinition, ToolModelOutput } from \"eve/tools\";\nimport { defineDynamic, defineTool } from \"eve/tools\";\nimport { parse, stringify } from \"superjson\";\n\nimport {\n discoverEveMcpTools,\n executeEveMcpTool,\n requestEveMcpApproval,\n} from \"@/plugins/mcp/runtime/mcp-tools\";\nimport { eveTurnGuest, eveTurnTool } from \"@/lib/eve/turn-tools\";\nimport type { McpToolContext } from \"@/plugins/mcp/runtime/mcp-tools\";\nimport { createModuleLogger } from \"@/lib/logger\";\n\nconst log = createModuleLogger(\"eve.mcp-registration\");\n\nconst mcpTools = defineDynamic({\n events: {\n \"step.started\": async (\n _event,\n context: Readonly<{\n session: Readonly<Pick<McpToolContext[\"session\"], \"id\" | \"auth\">>;\n abortSignal?: Readonly<AbortSignal>;\n messages: readonly unknown[];\n }>\n ) => {\n if (\n isGuestSession(context.session) ||\n eveTurnGuest.get() ||\n eveTurnTool.get()\n ) {\n return {};\n }\n const ownerId = context.session.auth.initiator?.principalId;\n const timeoutSignal = AbortSignal.timeout(30_000);\n const discoverySignal =\n (context.abortSignal &&\n AbortSignal.any([context.abortSignal, timeoutSignal])) ??\n timeoutSignal;\n const tools = await discoverEveMcpTools(ownerId, discoverySignal).catch(\n (error: unknown) => {\n if (timeoutSignal.aborted) {\n log.warn(\"MCP discovery timed out; continuing without MCP tools\");\n return [];\n }\n throw error;\n }\n );\n const messages = stringify(context.messages);\n const definitions: Record<\n string,\n ToolDefinition<\n Record<string, unknown>,\n Awaited<ReturnType<typeof executeEveMcpTool>>\n >\n > = {};\n for (const { name, connectorId, remoteName, ...description } of tools) {\n definitions[name] = defineTool({\n ...description,\n approval: {\n request: async (\n approvalContext: Readonly<\n Pick<McpToolContext, \"session\" | \"abortSignal\"> & {\n toolInput?: unknown;\n }\n >\n ) =>\n await requestEveMcpApproval(\n connectorId,\n remoteName,\n approvalContext.toolInput,\n approvalContext\n ),\n response: ({\n response,\n session,\n }: {\n readonly response: Readonly<{\n principal: Readonly<{ principalId: string }>;\n }>;\n readonly session: Readonly<{\n initiator: Readonly<{ principalId: string }> | null;\n }>;\n }) => {\n if (\n response.principal.principalId ===\n session.initiator?.principalId\n ) {\n return { status: \"allowed\" };\n }\n return {\n reason: \"Only the owner may respond\",\n status: \"rejected\",\n };\n },\n },\n execute: async (\n input: Readonly<Record<string, unknown>>,\n toolContext: McpToolContext\n ) =>\n await executeEveMcpTool(\n connectorId,\n remoteName,\n input,\n toolContext,\n parse(messages)\n ),\n toModelOutput: (output: Readonly<{ modelOutput: ToolModelOutput }>) =>\n output.modelOutput,\n });\n }\n return definitions;\n },\n },\n});\n\nexport { mcpTools };\n",
|
|
31
|
+
"type": "registry:file",
|
|
32
|
+
"target": "~/plugins/mcp/runtime/agent-tools.ts"
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
"path": "src/plugins/mcp/adapters/app/(chat)/settings/connectors/page.tsx",
|
|
36
|
+
"content": "import { ConnectorsSettingsPage } from \"@/plugins/mcp/routes/connectors-page\";\n\nconst Page = () => <ConnectorsSettingsPage />;\n\nexport default Page;\n",
|
|
37
|
+
"type": "registry:file",
|
|
38
|
+
"target": "~/app/(chat)/settings/connectors/page.tsx"
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
"path": "src/plugins/mcp/src/routes/connectors-page.tsx",
|
|
42
|
+
"content": "import { HydrationBoundary, dehydrate } from \"@tanstack/react-query\";\nimport { connection } from \"next/server\";\nimport React, { Suspense } from \"react\";\n\nimport { ConnectorsSettings } from \"@/plugins/mcp/ui/connectors-settings\";\nimport {\n SettingsPage,\n SettingsPageHeader,\n} from \"@/components/settings/settings-page\";\nimport { Skeleton } from \"@/components/ui/skeleton\";\nimport { makeQueryClient } from \"@/trpc/query-client\";\nimport { preloadQuery } from \"@/trpc/preload-query\";\nimport { trpc } from \"@/trpc/server\";\n\nconst ConnectorsSettingsHeader = (): React.JSX.Element => (\n <SettingsPageHeader>\n <h2 className=\"text-lg font-semibold\">Connectors & MCP</h2>\n <p className=\"text-muted-foreground text-sm\">\n Connect to Model Context Protocol servers to extend AI capabilities with\n external tools.\n </p>\n </SettingsPageHeader>\n);\n\nconst ConnectorsSettingsContent = async (): Promise<React.JSX.Element> => {\n await connection();\n // Keep this result out of the layout's earlier hydration boundary.\n const queryClient = makeQueryClient();\n await preloadQuery(queryClient.query(trpc.mcp.list.queryOptions()));\n\n return (\n <HydrationBoundary state={dehydrate(queryClient)}>\n <SettingsPage>\n <ConnectorsSettingsHeader />\n <ConnectorsSettings />\n </SettingsPage>\n </HydrationBoundary>\n );\n};\n\nconst ConnectorsSettingsPage = (): React.JSX.Element => (\n <Suspense\n fallback={\n <SettingsPage>\n <ConnectorsSettingsHeader />\n <div className=\"flex flex-col gap-3\">\n <Skeleton className=\"h-16 w-full\" />\n <Skeleton className=\"h-16 w-full\" />\n <Skeleton className=\"h-16 w-5/6\" />\n </div>\n </SettingsPage>\n }\n >\n <ConnectorsSettingsContent />\n </Suspense>\n);\n\nexport { ConnectorsSettingsPage };\n",
|
|
43
|
+
"type": "registry:file",
|
|
44
|
+
"target": "~/plugins/mcp/routes/connectors-page.tsx"
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
"path": "src/plugins/mcp/adapters/app/(chat)/settings/connectors/[connectorId]/page.tsx",
|
|
48
|
+
"content": "import { ConnectorDetailsPage } from \"@/plugins/mcp/routes/connector-page\";\n\nconst Page = (props: { readonly params: Promise<{ connectorId: string }> }) => (\n <ConnectorDetailsPage {...props} />\n);\n\nexport default Page;\n",
|
|
49
|
+
"type": "registry:file",
|
|
50
|
+
"target": "~/app/(chat)/settings/connectors/[connectorId]/page.tsx"
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
"path": "src/plugins/mcp/src/routes/connector-page.tsx",
|
|
54
|
+
"content": "import { HydrationBoundary, dehydrate } from \"@tanstack/react-query\";\nimport { connection } from \"next/server\";\nimport React, { Suspense } from \"react\";\n\nimport { McpDetailsPage } from \"@/plugins/mcp/ui/mcp-details-page\";\nimport {\n SettingsPage,\n SettingsPageHeader,\n} from \"@/components/settings/settings-page\";\nimport { Skeleton } from \"@/components/ui/skeleton\";\nimport { makeQueryClient } from \"@/trpc/query-client\";\nimport { preloadQuery } from \"@/trpc/preload-query\";\nimport { trpc } from \"@/trpc/server\";\n\nconst ConnectorDetailsHeader = (): React.JSX.Element => (\n <SettingsPageHeader>\n <h2 className=\"text-lg font-semibold\">Connector details</h2>\n <p className=\"text-muted-foreground text-sm\">\n Tools, resources, and authorization status.\n </p>\n </SettingsPageHeader>\n);\n\nconst ConnectorDetailsBodyFallback = (): React.JSX.Element => (\n <div className=\"flex flex-col gap-3\">\n <Skeleton className=\"h-10 w-48\" />\n <Skeleton className=\"h-24 w-full\" />\n <Skeleton className=\"h-24 w-full\" />\n <Skeleton className=\"h-16 w-5/6\" />\n </div>\n);\n\nconst ConnectorDetailsContent = async ({\n params,\n}: {\n readonly params: Readonly<Promise<{ readonly connectorId: string }>>;\n}): Promise<React.JSX.Element> => {\n const { connectorId } = await params;\n await connection();\n // Keep this result out of the layout's earlier hydration boundary.\n const queryClient = makeQueryClient();\n await preloadQuery(queryClient.query(trpc.mcp.list.queryOptions()));\n return (\n <HydrationBoundary state={dehydrate(queryClient)}>\n <SettingsPage>\n <ConnectorDetailsHeader />\n <Suspense fallback={<ConnectorDetailsBodyFallback />}>\n <McpDetailsPage connectorId={connectorId} />\n </Suspense>\n </SettingsPage>\n </HydrationBoundary>\n );\n};\n\nconst ConnectorDetailsPage = ({\n params,\n}: {\n readonly params: Readonly<Promise<{ readonly connectorId: string }>>;\n}): React.JSX.Element => (\n <Suspense\n fallback={\n <SettingsPage>\n <ConnectorDetailsHeader />\n <ConnectorDetailsBodyFallback />\n </SettingsPage>\n }\n >\n <ConnectorDetailsContent params={params} />\n </Suspense>\n);\n\nexport { ConnectorDetailsPage };\n",
|
|
55
|
+
"type": "registry:file",
|
|
56
|
+
"target": "~/plugins/mcp/routes/connector-page.tsx"
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
"path": "src/plugins/mcp/adapters/app/api/mcp/oauth/callback/route.ts",
|
|
60
|
+
"content": "export { GET } from \"@/plugins/mcp/routes/oauth-callback\";\n",
|
|
61
|
+
"type": "registry:file",
|
|
62
|
+
"target": "~/app/api/mcp/oauth/callback/route.ts"
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
"path": "src/plugins/mcp/src/routes/oauth-callback.ts",
|
|
66
|
+
"content": "import { MissingCredentialsError } from \"@/lib/required-credentials\";\nimport type { NextRequest } from \"next/server\";\nimport { NextResponse } from \"next/server\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\n\nimport { requireMcpCredentials } from \"@/plugins/mcp/setup\";\nimport {\n createMcpClientForCallback,\n removeMcpClient,\n} from \"@/plugins/mcp/oauth/mcp-client-manager\";\nimport {\n deletePendingSessionByState,\n getMcpConnectorById,\n getSessionByState,\n} from \"@/plugins/mcp/db/mcp-queries\";\nimport { createModuleLogger } from \"@/lib/logger\";\nimport { invalidateAllMcpCaches } from \"@/plugins/mcp/oauth/cache\";\nimport { loadMcpOAuthCallbackSearchParams } from \"@/plugins/mcp/search/mcp-search-params.server\";\n\nconst hasNonEmptyValue = (value: string | null | undefined): value is string =>\n typeof value === \"string\" && value !== \"\";\n\nconst log = createModuleLogger(\"mcp-oauth-callback\");\n\nconst redirectToConnector = (\n request: ReadonlyNativeSurface<Pick<NextRequest, \"nextUrl\">>,\n {\n connectorId,\n connected,\n errorMessage,\n }: {\n readonly connectorId?: string;\n readonly connected?: boolean;\n readonly errorMessage?: string;\n }\n): NextResponse => {\n const path = hasNonEmptyValue(connectorId)\n ? `/settings/connectors/${connectorId}`\n : \"/settings/connectors\";\n const url = new URL(path, request.nextUrl.origin);\n if (connected === true) {\n url.searchParams.set(\"connected\", \"1\");\n }\n if (hasNonEmptyValue(errorMessage)) {\n url.searchParams.set(\"error\", errorMessage);\n }\n return NextResponse.redirect(url);\n};\n\nconst oauthFailureResponse = (\n request: ReadonlyNativeSurface<Pick<NextRequest, \"nextUrl\">>,\n connector: Readonly<\n Pick<NonNullable<Awaited<ReturnType<typeof getMcpConnectorById>>>, \"id\">\n >,\n oauthError: unknown\n): NextResponse => {\n const errorMessage =\n oauthError instanceof Error ? oauthError.message : \"Token exchange failed\";\n log.error(\n {\n connectorId: connector.id,\n error: oauthError,\n errorMessage,\n errorStack: oauthError instanceof Error ? oauthError.stack : undefined,\n },\n \"OAuth token exchange failed\"\n );\n\n return redirectToConnector(request, {\n connectorId: connector.id,\n errorMessage:\n \"Could not complete connector authorization. Please try again.\",\n });\n};\n\nexport const GET = async (\n request: ReadonlyNativeSurface<NextRequest>\n): Promise<NextResponse> => {\n const {\n code,\n state,\n error,\n error_description: errorDesc,\n } = loadMcpOAuthCallbackSearchParams(request);\n\n log.info(\n { error, hasCode: Boolean(code), hasState: Boolean(state) },\n \"OAuth callback received\"\n );\n\n try {\n requireMcpCredentials();\n } catch (setupError) {\n if (setupError instanceof MissingCredentialsError) {\n return redirectToConnector(request, { errorMessage: setupError.message });\n }\n throw setupError;\n }\n\n if (hasNonEmptyValue(error)) {\n log.error({ error, errorDesc }, \"OAuth error from provider\");\n const pending = hasNonEmptyValue(state)\n ? await getSessionByState({ state })\n : undefined;\n if (pending && !pending.tokens && hasNonEmptyValue(state)) {\n const deleted = await deletePendingSessionByState({ state });\n if (deleted) {\n await removeMcpClient(deleted.mcpConnectorId, state);\n invalidateAllMcpCaches(deleted.mcpConnectorId);\n }\n }\n return redirectToConnector(request, {\n connectorId: pending?.mcpConnectorId,\n errorMessage:\n \"Authorization was not completed. Please try connecting again.\",\n });\n }\n if (!(hasNonEmptyValue(code) && hasNonEmptyValue(state))) {\n log.error(\n { code: Boolean(code), state: Boolean(state) },\n \"Missing code or state\"\n );\n return redirectToConnector(request, {\n errorMessage: \"Missing authorization code or state parameter\",\n });\n }\n\n // Look up the session by state\n const session = await getSessionByState({ state });\n\n if (!session) {\n log.error({ state }, \"Session not found for state\");\n return redirectToConnector(request, {\n errorMessage: \"Invalid or expired session. Please try again.\",\n });\n }\n\n // Get the connector to get its configuration\n const connector = await getMcpConnectorById({ id: session.mcpConnectorId });\n if (!connector) {\n log.error({ connectorId: session.mcpConnectorId }, \"Connector not found\");\n return redirectToConnector(request, {\n errorMessage: \"MCP connector not found\",\n });\n }\n\n try {\n // Create a fresh MCP client for callback handling\n // Don't use cached client - it might have stale/different state\n const mcpClient = createMcpClientForCallback({\n id: connector.id,\n name: connector.name,\n oauthClientId: connector.oauthClientId,\n oauthClientSecret: connector.oauthClientSecret,\n type: connector.type,\n url: connector.url,\n });\n\n // Complete the OAuth flow (don't connect first - just exchange the code)\n await mcpClient.finishAuth(code, state);\n invalidateAllMcpCaches(connector.id);\n\n log.info(\n { connectorId: connector.id },\n \"OAuth flow completed successfully\"\n );\n\n // Important: clear any cached MCP client that might be stuck in `authorizing`\n // from a pre-auth discovery attempt. Tokens are saved by finishAuth, but\n // cached clients may still keep an authorization URL in memory.\n await removeMcpClient(connector.id);\n\n return redirectToConnector(request, {\n connected: true,\n connectorId: connector.id,\n });\n } catch (oauthError) {\n return oauthFailureResponse(request, connector, oauthError);\n }\n};\n",
|
|
67
|
+
"type": "registry:file",
|
|
68
|
+
"target": "~/plugins/mcp/routes/oauth-callback.ts"
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
"path": "src/plugins/mcp/src/ui/connectors-settings.tsx",
|
|
72
|
+
"content": "\"use client\";\n\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport {\n AlertTriangle,\n ArrowUpRight,\n Loader2,\n MoreHorizontal,\n Plus,\n Radio,\n Trash2,\n} from \"lucide-react\";\nimport { useRouter, useSearchParams } from \"next/navigation\";\nimport { useQueryStates } from \"nuqs\";\nimport React, { Fragment, useCallback, useEffect, useMemo } from \"react\";\nimport { toast } from \"sonner\";\n\nimport { InternalLink } from \"@/components/internal-link\";\nimport { ConnectorHeader } from \"@/plugins/mcp/ui/connector-header\";\nimport { McpConnectDialog } from \"@/plugins/mcp/ui/mcp-connect-dialog\";\nimport { McpCreateDialog } from \"@/plugins/mcp/ui/mcp-create-dialog\";\nimport { SettingsPageContent } from \"@/components/settings/settings-page\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button, buttonVariants } from \"@/components/ui/button\";\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuGroup,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\";\nimport type { McpConnector } from \"@/plugins/mcp/db/mcp-schema\";\nimport type { McpConnectorsDialog } from \"@/plugins/mcp/search/mcp-search-params\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { Separator } from \"@/components/ui/separator\";\nimport { installedPlugins } from \"@/composition/generated/installed\";\nimport { mcpConnectorsSettingsSearchParams } from \"@/plugins/mcp/search/mcp-search-params\";\nimport { useTRPC } from \"@/trpc/react\";\n\nconst CustomConnectorRow = ({\n connector,\n onConnect,\n onUninstall,\n onDisconnect,\n isDisconnecting,\n}: {\n readonly connector: Readonly<\n Pick<McpConnector, \"id\" | \"name\" | \"type\" | \"url\">\n >;\n readonly onConnect: () => void;\n readonly onUninstall: () => void;\n readonly onDisconnect: () => void;\n readonly isDisconnecting: boolean;\n}): React.JSX.Element => {\n const trpc = useTRPC();\n\n const { data: authStatus } = useQuery({\n ...trpc.mcp.checkAuth.queryOptions({ id: connector.id }),\n staleTime: 30_000,\n });\n\n const { isLoading: isTestingConnection, data: connectionStatus } = useQuery({\n ...trpc.mcp.testConnection.queryOptions({ id: connector.id }),\n retry: false,\n staleTime: 30_000,\n });\n\n const needsOAuth = connectionStatus?.needsAuth ?? false;\n const isConnected = connectionStatus?.status === \"connected\";\n const isIncompatible = connectionStatus?.status === \"incompatible\";\n\n const statusText = ((): string => {\n if (isTestingConnection) {\n return \"Checking connection…\";\n }\n if (isIncompatible) {\n return \"Incompatible server\";\n }\n if (needsOAuth) {\n return \"Authorization required\";\n }\n if (isConnected) {\n return \"Connected\";\n }\n return connectionStatus?.error ?? \"Unable to reach server\";\n })();\n\n const actionLabel = ((): string => {\n if (isTestingConnection) {\n return \"Loading\";\n }\n if (needsOAuth) {\n return \"Connect\";\n }\n return \"Configure\";\n })();\n\n const href: `/settings/connectors/${string}` = `/settings/connectors/${connector.id}`;\n\n const showOAuthButton = needsOAuth && !isIncompatible;\n const showDetailsButton = !(needsOAuth || isIncompatible);\n\n return (\n <div className=\"flex items-center gap-4 py-3\">\n <div className=\"flex min-w-0 flex-1 items-center gap-3 overflow-hidden text-left\">\n <ConnectorHeader\n isCustom\n name={connector.name}\n statusText={statusText}\n type={connector.type}\n url={connector.url}\n />\n </div>\n\n <div className=\"flex shrink-0 items-center gap-2\">\n {isIncompatible ? (\n <Badge className=\"gap-1\" variant=\"destructive\">\n <AlertTriangle className=\"size-3\" />\n Error\n </Badge>\n ) : null}\n\n {showOAuthButton ? (\n <Button disabled={isTestingConnection} onClick={onConnect} size=\"sm\">\n {isTestingConnection ? (\n <span className=\"inline-flex items-center gap-2\">\n <Loader2 className=\"size-4 animate-spin\" />\n Loading\n </span>\n ) : (\n <span className=\"inline-flex items-center gap-2\">\n Connect\n <ArrowUpRight className=\"-mr-1 size-4\" />\n </span>\n )}\n </Button>\n ) : null}\n\n {showDetailsButton ? (\n <InternalLink\n href={href}\n className={buttonVariants({ size: \"sm\", variant: \"outline\" })}\n aria-disabled={isTestingConnection}\n tabIndex={isTestingConnection ? -1 : undefined}\n onClick={(event) => {\n if (isTestingConnection) {\n event.preventDefault();\n }\n }}\n >\n {isTestingConnection ? (\n <span className=\"inline-flex items-center gap-2\">\n <Loader2 className=\"size-4 animate-spin\" />\n Loading\n </span>\n ) : (\n <span className=\"inline-flex items-center gap-2\">\n {actionLabel}\n </span>\n )}\n </InternalLink>\n ) : null}\n <DropdownMenu>\n <DropdownMenuTrigger\n render={\n <Button\n aria-label=\"More connector actions\"\n size=\"icon\"\n variant=\"ghost\"\n />\n }\n >\n <MoreHorizontal className=\"size-4\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n <DropdownMenuGroup>\n {authStatus?.isAuthenticated === true ? (\n <>\n <DropdownMenuItem\n disabled={isDisconnecting}\n onClick={onDisconnect}\n >\n Disconnect\n </DropdownMenuItem>\n <DropdownMenuSeparator />\n </>\n ) : null}\n {needsOAuth ? (\n <>\n <DropdownMenuItem\n onClick={(\n event: Readonly<Pick<Event, \"preventDefault\">>\n ): void => {\n event.preventDefault();\n onConnect();\n }}\n >\n Connect\n </DropdownMenuItem>\n <DropdownMenuSeparator />\n </>\n ) : null}\n <DropdownMenuItem variant=\"destructive\" onClick={onUninstall}>\n <Trash2 className=\"size-4\" />\n Uninstall\n </DropdownMenuItem>\n </DropdownMenuGroup>\n </DropdownMenuContent>\n </DropdownMenu>\n </div>\n </div>\n );\n};\n\nconst BuiltInConnectorRow = ({\n connector,\n}: {\n readonly connector: {\n readonly id: string;\n readonly name: string;\n readonly type: \"http\" | \"sse\";\n readonly url: string;\n };\n}): React.JSX.Element => {\n const href: `/settings/connectors/${string}` = `/settings/connectors/${connector.id}`;\n return (\n <div className=\"flex w-full items-center gap-3 py-3 text-left\">\n <ConnectorHeader\n isCustom={false}\n name={connector.name}\n type={connector.type}\n url={connector.url}\n />\n <InternalLink\n href={href}\n className={buttonVariants({ size: \"sm\", variant: \"outline\" })}\n >\n View\n </InternalLink>\n </div>\n );\n};\n\nexport const ConnectorsSettings = (): React.JSX.Element => {\n const trpc = useTRPC();\n const queryClient = useQueryClient();\n const router = useRouter();\n const searchParams = useSearchParams();\n useEffect((): void => {\n const callbackError = searchParams.get(\"error\");\n if (typeof callbackError === \"string\" && callbackError !== \"\") {\n toast.error(callbackError);\n router.replace(\"/settings/connectors\");\n }\n }, [router, searchParams]);\n\n const [qs, setQs] = useQueryStates(mcpConnectorsSettingsSearchParams, {\n history: \"replace\",\n shallow: true,\n });\n\n const {\n data: connectors,\n isLoading,\n error,\n refetch: refetchConnectors,\n } = useQuery({\n ...trpc.mcp.list.queryOptions(),\n enabled: installedPlugins.has(\"mcp\"),\n });\n\n const createOpen = qs.dialog === \"config\";\n const connectOpen = qs.dialog === \"connect\" && Boolean(qs.connectorId);\n\n const connectConnector = useMemo(() => {\n if (\n !(\n connectOpen &&\n typeof qs.connectorId === \"string\" &&\n qs.connectorId !== \"\" &&\n connectors\n )\n ) {\n return null;\n }\n return (\n connectors.find(\n (connector: { readonly id: string }): boolean =>\n connector.id === qs.connectorId\n ) ?? null\n );\n }, [connectOpen, qs.connectorId, connectors]);\n\n const queryKey = trpc.mcp.list.queryKey();\n\n const { mutate: deleteConnector } = useMutation(\n trpc.mcp.delete.mutationOptions({\n onError: (\n _err: unknown,\n _data,\n context: { readonly prev: typeof connectors } | undefined\n ): void => {\n queryClient.setQueryData(queryKey, context?.prev);\n toast.error(\"Failed to uninstall connector\");\n },\n onMutate: async (data) => {\n await queryClient.cancelQueries({ queryKey });\n const prev = queryClient.getQueryData(queryKey);\n queryClient.setQueryData(\n queryKey,\n (old: ReadonlyNativeSurface<typeof connectors>) => {\n if (!old) {\n return old;\n }\n return old.filter(\n (connector: { readonly id: string }): boolean =>\n connector.id !== data.id\n );\n }\n );\n return { prev };\n },\n onSettled: (): void => {\n void queryClient.invalidateQueries({ queryKey });\n void queryClient.invalidateQueries({\n queryKey: trpc.mcp.listConnected.queryKey(),\n });\n },\n onSuccess: (): void => {\n toast.success(\"Connector uninstalled\");\n },\n })\n );\n const { mutate: disconnectConnector, isPending: isDisconnecting } =\n useMutation(\n trpc.mcp.disconnect.mutationOptions({\n onError: (err: { readonly message: string }): void => {\n toast.error(err.message || \"Failed to disconnect\");\n },\n onSettled: (_data: unknown, _err: unknown, vars): void => {\n void queryClient.invalidateQueries({ queryKey });\n void queryClient.invalidateQueries({\n queryKey: trpc.mcp.listConnected.queryKey(),\n });\n void queryClient.invalidateQueries({\n queryKey: trpc.mcp.checkAuth.queryKey({ id: vars.id }),\n });\n void queryClient.invalidateQueries({\n queryKey: trpc.mcp.discover.queryKey({ id: vars.id }),\n });\n },\n onSuccess: (_data: Readonly<{ success: boolean }>, vars): void => {\n void queryClient.invalidateQueries({\n queryKey: trpc.mcp.testConnection.queryKey({ id: vars.id }),\n });\n toast.success(\"Disconnected\");\n },\n })\n );\n\n const setDialogState = useCallback(\n ({\n dialog,\n connectorId,\n }: {\n readonly dialog: McpConnectorsDialog | null;\n readonly connectorId?: string | null;\n }): void => {\n void setQs({\n connectorId: connectorId ?? null,\n dialog,\n });\n },\n [setQs]\n );\n\n const handleOpenCreateDialog = useCallback((): void => {\n setDialogState({ dialog: \"config\" });\n }, [setDialogState]);\n\n const handleDialogClose = (): void => {\n setDialogState({ dialog: null });\n };\n\n const handleOpenConnectDialog = useCallback(\n (connectorId: string): void => {\n setDialogState({\n connectorId,\n dialog: \"connect\",\n });\n },\n [setDialogState]\n );\n\n const handleConnectDialogClose = useCallback((): void => {\n setDialogState({ dialog: null });\n }, [setDialogState]);\n\n if (!installedPlugins.has(\"mcp\")) {\n return (\n <SettingsPageContent className=\"gap-4\">\n <div className=\"flex flex-col items-center justify-center py-12 text-center\">\n <p className=\"text-sm font-medium\">MCP is not enabled</p>\n </div>\n </SettingsPageContent>\n );\n }\n if (isLoading) {\n return (\n <SettingsPageContent className=\"gap-4\">\n <div className=\"animate-pulse space-y-3\">\n {[1, 2, 3].map((placeholderIndex) => (\n <div\n className=\"bg-muted/50 h-20 rounded-lg\"\n key={placeholderIndex}\n />\n ))}\n </div>\n </SettingsPageContent>\n );\n }\n\n if (error && !connectors) {\n return (\n <SettingsPageContent className=\"gap-4\">\n <div\n role=\"alert\"\n className=\"flex flex-col items-center justify-center py-12 text-center\"\n >\n <p className=\"text-sm font-medium\">Could not load connectors</p>\n <p className=\"text-muted-foreground mt-1 text-xs\">{error.message}</p>\n {}\n <Button\n onClick={(): void => {\n void refetchConnectors();\n }}\n variant=\"outline\"\n >\n Retry\n </Button>\n </div>\n </SettingsPageContent>\n );\n }\n\n const customConnectors = (connectors ?? []).filter(\n (connector: { readonly userId: string | null }): boolean =>\n connector.userId !== null\n );\n const globalConnectors = (connectors ?? []).filter(\n (connector: { readonly userId: string | null }): boolean =>\n connector.userId === null\n );\n\n return (\n <SettingsPageContent className=\"gap-6\">\n <div className=\"flex items-center justify-between gap-3\">\n <div>\n <p className=\"text-sm font-medium\">Custom connectors</p>\n <p className=\"text-muted-foreground mt-0.5 text-xs\">\n Connect MCP servers you trust to extend your AI with tools.\n </p>\n </div>\n <Button onClick={handleOpenCreateDialog} size=\"sm\">\n <Plus className=\"size-4\" />\n Add custom connector\n </Button>\n </div>\n\n <div className=\"flex flex-col\">\n {customConnectors.length > 0 ? (\n customConnectors.map(\n (\n connector: Readonly<\n Pick<McpConnector, \"id\" | \"name\" | \"type\" | \"url\">\n >,\n index\n ) => (\n <Fragment key={connector.id}>\n <CustomConnectorRow\n connector={connector}\n isDisconnecting={isDisconnecting}\n onConnect={(): void => {\n handleOpenConnectDialog(connector.id);\n }}\n onDisconnect={(): void => {\n disconnectConnector({ id: connector.id });\n }}\n onUninstall={(): void => {\n deleteConnector({ id: connector.id });\n }}\n />\n {index < customConnectors.length - 1 ? <Separator /> : null}\n </Fragment>\n )\n )\n ) : (\n <div className=\"flex flex-col items-center justify-center py-10 text-center\">\n <div className=\"bg-muted mb-4 rounded-full p-3\">\n <Radio className=\"text-muted-foreground size-6\" />\n </div>\n <p className=\"text-sm font-medium\">No custom connectors</p>\n <p className=\"text-muted-foreground mt-1 max-w-sm text-xs\">\n Add a custom MCP connector to access tools from your services.\n </p>\n </div>\n )}\n </div>\n\n {globalConnectors.length > 0 ? (\n <div>\n <p className=\"text-sm font-medium\">Built-in connectors</p>\n <div className=\"divide-y\">\n {globalConnectors.map(\n (\n connector: Readonly<\n Pick<McpConnector, \"id\" | \"name\" | \"type\" | \"url\">\n >\n ) => (\n <BuiltInConnectorRow connector={connector} key={connector.id} />\n )\n )}\n </div>\n </div>\n ) : null}\n\n <McpCreateDialog onClose={handleDialogClose} open={createOpen} />\n\n <McpConnectDialog\n connector={connectConnector}\n onClose={handleConnectDialogClose}\n open={connectOpen}\n />\n </SettingsPageContent>\n );\n};\n",
|
|
73
|
+
"type": "registry:file",
|
|
74
|
+
"target": "~/plugins/mcp/ui/connectors-settings.tsx"
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
"path": "src/plugins/mcp/src/ui/connector-header.tsx",
|
|
78
|
+
"content": "\"use client\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Favicon } from \"@/components/favicon\";\nimport { Globe } from \"lucide-react\";\nimport React from \"react\";\nimport { getGoogleFaviconUrl } from \"@/components/get-google-favicon-url\";\nimport { getUrlWithoutParams } from \"@/components/get-url-without-params\";\n\nexport const ConnectorHeader = ({\n name,\n url,\n type,\n isCustom,\n statusText,\n}: {\n readonly name: string;\n readonly url: string;\n readonly type: string;\n readonly isCustom: boolean;\n readonly statusText?: string;\n}): React.JSX.Element => {\n const faviconUrl = type === \"http\" ? getGoogleFaviconUrl(url) : \"\";\n\n return (\n <div className=\"flex min-w-0 flex-1 items-center gap-3 overflow-hidden\">\n <div className=\"bg-muted flex size-10 shrink-0 items-center justify-center rounded-lg\">\n {faviconUrl ? (\n <Favicon\n className=\"size-5 rounded-sm\"\n fallback={<Globe className=\"text-muted-foreground size-5\" />}\n url={faviconUrl}\n />\n ) : (\n <Globe className=\"text-muted-foreground size-5\" />\n )}\n </div>\n\n <div className=\"min-w-0 flex-1 overflow-hidden\">\n <div className=\"flex items-center gap-2 overflow-hidden\">\n <span className=\"truncate text-sm font-medium\">{name}</span>\n {isCustom ? (\n <Badge\n className=\"h-5 shrink-0 px-2 text-[10px]\"\n variant=\"secondary\"\n >\n CUSTOM\n </Badge>\n ) : (\n <Badge className=\"h-5 shrink-0 px-2 text-[10px]\" variant=\"outline\">\n Built-in\n </Badge>\n )}\n </div>\n <p className=\"text-muted-foreground mt-0.5 truncate text-xs\">\n {getUrlWithoutParams(url)}\n </p>\n {typeof statusText === \"string\" && statusText !== \"\" ? (\n <p className=\"text-muted-foreground mt-0.5 text-[11px]\">\n {statusText}\n </p>\n ) : null}\n </div>\n </div>\n );\n};\n",
|
|
79
|
+
"type": "registry:file",
|
|
80
|
+
"target": "~/plugins/mcp/ui/connector-header.tsx"
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
"path": "src/plugins/mcp/src/ui/mcp-connect-dialog.tsx",
|
|
84
|
+
"content": "\"use client\";\n\nimport { useMutation } from \"@tanstack/react-query\";\nimport {\n AlertTriangle,\n ExternalLink,\n Globe,\n Loader2,\n Lock,\n Shield,\n} from \"lucide-react\";\nimport React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { toast } from \"sonner\";\n\nimport { Favicon } from \"@/components/favicon\";\nimport { getGoogleFaviconUrl } from \"@/components/get-google-favicon-url\";\nimport { getUrlWithoutParams } from \"@/components/get-url-without-params\";\nimport { Button } from \"@/components/ui/button\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"@/components/ui/dialog\";\nimport type { McpConnector } from \"@/plugins/mcp/db/mcp-schema\";\nimport { config } from \"@/lib/config\";\nimport { useTRPC } from \"@/trpc/react\";\n\nexport const McpConnectDialog = ({\n open,\n onClose,\n connector,\n}: {\n readonly open: boolean;\n readonly onClose: () => void;\n readonly connector: Readonly<\n Pick<McpConnector, \"id\" | \"name\" | \"type\" | \"url\">\n > | null;\n}): React.JSX.Element => {\n const trpc = useTRPC();\n const [isRedirecting, setIsRedirecting] = useState(false);\n const attempt = useRef(0);\n useEffect(() => {\n if (!open || (connector?.id ?? \"\") === \"\") {\n attempt.current += 1;\n }\n return (): void => {\n attempt.current += 1;\n };\n }, [open, connector?.id]);\n const handleClose = useCallback((): void => {\n attempt.current += 1;\n setIsRedirecting(false);\n onClose();\n }, [onClose]);\n\n const faviconUrl = useMemo((): string => {\n if (!connector) {\n return \"\";\n }\n if (connector.type === \"http\") {\n return getGoogleFaviconUrl(connector.url);\n }\n return \"\";\n }, [connector]);\n\n const { mutate: authorize, isPending } = useMutation(\n trpc.mcp.authorize.mutationOptions()\n );\n\n const handleContinue = useCallback((): void => {\n if (!connector) {\n return;\n }\n attempt.current += 1;\n const currentAttempt = attempt.current;\n authorize(\n { id: connector.id },\n {\n onError: (err: { readonly message: string }): void => {\n if (attempt.current === currentAttempt) {\n toast.error(err.message || \"Failed to start connection\");\n }\n },\n onSuccess: ({\n authorizationUrl,\n }: Readonly<{ authorizationUrl: string }>): void => {\n if (attempt.current !== currentAttempt) {\n return;\n }\n let url: URL;\n try {\n url = new URL(authorizationUrl);\n } catch {\n toast.error(\"Invalid authorization URL\");\n return;\n }\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n toast.error(\"Invalid authorization URL\");\n return;\n }\n setIsRedirecting(true);\n globalThis.location.href = url.href;\n },\n }\n );\n }, [authorize, connector]);\n\n return (\n <Dialog\n onOpenChange={(isOpen): void => {\n if (!isOpen) {\n handleClose();\n }\n }}\n open={open}\n >\n <DialogContent className=\"sm:max-w-md\">\n <DialogHeader className=\"overflow-hidden\">\n <div className=\"flex items-center gap-3 overflow-hidden\">\n <div className=\"bg-muted flex size-10 shrink-0 items-center justify-center rounded-md\">\n {faviconUrl ? (\n <Favicon\n className=\"size-5 rounded-sm\"\n fallback={<Globe className=\"text-muted-foreground size-5\" />}\n url={faviconUrl}\n />\n ) : (\n <Globe className=\"text-muted-foreground size-5\" />\n )}\n </div>\n <div className=\"min-w-0 flex-1 overflow-hidden\">\n <DialogTitle className=\"truncate\">\n Connect {connector?.name ?? \"connector\"}\n </DialogTitle>\n <DialogDescription className=\"truncate\">\n {connector !== null && connector.url !== \"\"\n ? getUrlWithoutParams(connector.url)\n : null}\n </DialogDescription>\n </div>\n </div>\n </DialogHeader>\n\n <div className=\"space-y-6 py-2\">\n <div className=\"flex gap-4\">\n <Shield className=\"text-muted-foreground mt-0.5 size-4 shrink-0\" />\n <div>\n <p className=\"text-sm font-medium\">\n Permissions always respected\n </p>\n <p className=\"text-muted-foreground mt-1 text-sm\">\n {config.appName} is strictly limited to permissions you\n explicitly set. Disable access anytime to revoke permissions.\n </p>\n </div>\n </div>\n\n <div className=\"flex gap-4\">\n <Lock className=\"text-muted-foreground mt-0.5 size-4 shrink-0\" />\n <div>\n <p className=\"text-sm font-medium\">\n How {config.appName} uses data\n </p>\n <p className=\"text-muted-foreground mt-1 text-sm\">\n By default, we do not train on your data. Data from{\" \"}\n {connector?.name ?? \"this connector\"} may be used to provide you\n relevant and useful information.\n </p>\n </div>\n </div>\n\n <div className=\"flex gap-4\">\n <AlertTriangle className=\"text-muted-foreground mt-0.5 size-4 shrink-0\" />\n <div>\n <p className=\"text-sm font-medium\">\n Connectors may introduce risk\n </p>\n <p className=\"text-muted-foreground mt-1 text-sm\">\n Connectors are designed to respect your privacy, but sites may\n attempt to steal your data.\n </p>\n </div>\n </div>\n </div>\n\n <DialogFooter className=\"mt-4 flex-col gap-3 sm:flex-col\">\n <Button\n className=\"w-full\"\n disabled={isPending || isRedirecting || !connector}\n onClick={handleContinue}\n >\n {isPending || isRedirecting ? (\n <>\n <Loader2 className=\"size-4 animate-spin\" />\n Redirecting...\n </>\n ) : (\n <>\n Continue to {connector?.name ?? \"connector\"}\n <ExternalLink className=\"size-4\" />\n </>\n )}\n </Button>\n <Button className=\"w-full\" onClick={handleClose} variant=\"ghost\">\n Cancel\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n};\n",
|
|
85
|
+
"type": "registry:file",
|
|
86
|
+
"target": "~/plugins/mcp/ui/mcp-connect-dialog.tsx"
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
"path": "src/plugins/mcp/src/ui/mcp-create-dialog.tsx",
|
|
90
|
+
"content": "\"use client\";\n\nimport { zodResolver } from \"@hookform/resolvers/zod\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { ChevronDown } from \"lucide-react\";\nimport React, { useEffect, useState } from \"react\";\nimport { Controller, useForm } from \"react-hook-form\";\nimport { toast } from \"sonner\";\nimport { z } from \"zod\";\n\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport {\n Collapsible,\n CollapsibleContent,\n CollapsibleTrigger,\n} from \"@/components/ui/collapsible\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"@/components/ui/dialog\";\nimport {\n Field,\n FieldError,\n FieldGroup,\n FieldLabel,\n} from \"@/components/ui/field\";\nimport { Input } from \"@/components/ui/input\";\nimport {\n Select,\n SelectContent,\n SelectGroup,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from \"@/components/ui/select\";\nimport { Spinner } from \"@/components/ui/spinner\";\nimport { MCP_NAME_MAX_LENGTH } from \"@/lib/ai/mcp-name-id\";\nimport { config } from \"@/lib/config\";\nimport { useTRPC } from \"@/trpc/react\";\n\nconst mcpConnectorFormSchema = z.object({\n name: z\n .string()\n .trim()\n .min(1, { message: \"Name is required\" })\n .max(MCP_NAME_MAX_LENGTH, {\n message: `Name must be at most ${MCP_NAME_MAX_LENGTH} characters`,\n }),\n oauthClientId: z.string().optional(),\n oauthClientSecret: z.string().optional(),\n type: z.enum([\"http\", \"sse\"]),\n url: z\n .string()\n .min(1, { message: \"URL is required\" })\n .check(z.url({ error: \"Please enter a valid URL\" })),\n});\n\ntype McpConnectorFormValues = z.infer<typeof mcpConnectorFormSchema>;\n\ntype ReadonlyFormEvent = Readonly<{\n bubbles: boolean;\n cancelable: boolean;\n defaultPrevented: boolean;\n eventPhase: number;\n isTrusted: boolean;\n timeStamp: number;\n type: string;\n nativeEvent: object;\n target: unknown;\n currentTarget: unknown;\n preventDefault: () => void;\n persist: () => void;\n stopPropagation: () => void;\n isDefaultPrevented: () => boolean;\n isPropagationStopped: () => boolean;\n}>;\n\nexport const McpCreateDialog = ({\n open,\n onClose,\n}: {\n readonly open: boolean;\n readonly onClose: () => void;\n}): React.JSX.Element => {\n const [, startEventAction] = React.useTransition();\n const trpc = useTRPC();\n const queryClient = useQueryClient();\n const queryKey = trpc.mcp.list.queryKey();\n const { appName } = config;\n\n const [advancedOpen, setAdvancedOpen] = useState(false);\n const [previousOpen, setPreviousOpen] = useState(open);\n if (previousOpen !== open) {\n setPreviousOpen(open);\n if (open) {\n setAdvancedOpen(false);\n }\n }\n\n const form = useForm<McpConnectorFormValues>({\n defaultValues: {\n name: \"\",\n oauthClientId: \"\",\n oauthClientSecret: \"\",\n type: \"http\",\n url: \"\",\n },\n resolver: zodResolver(mcpConnectorFormSchema),\n });\n\n useEffect((): void => {\n if (!open) {\n return;\n }\n\n form.reset({\n name: \"\",\n oauthClientId: \"\",\n oauthClientSecret: \"\",\n type: \"http\",\n url: \"\",\n });\n }, [open, form]);\n\n const { mutate: createConnector, isPending } = useMutation(\n trpc.mcp.create.mutationOptions({\n onError: (err: { readonly message: string }): void => {\n toast.error(err.message || \"Failed to add connector\");\n },\n onSuccess: (): void => {\n void queryClient.invalidateQueries({ queryKey });\n },\n })\n );\n\n const handleSubmit = (values: Readonly<McpConnectorFormValues>): void => {\n const trimmed: McpConnectorFormValues = {\n ...values,\n name: values.name.trim(),\n oauthClientId:\n (values.oauthClientId?.trim() ?? \"\") === \"\"\n ? undefined\n : values.oauthClientId,\n oauthClientSecret:\n (values.oauthClientSecret?.trim() ?? \"\") === \"\"\n ? undefined\n : values.oauthClientSecret,\n url: values.url.trim(),\n };\n\n createConnector(\n {\n name: trimmed.name,\n oauthClientId: trimmed.oauthClientId,\n oauthClientSecret: trimmed.oauthClientSecret,\n type: trimmed.type,\n url: trimmed.url,\n },\n {\n onSuccess: (): void => {\n toast.success(\"Connector added\");\n onClose();\n },\n }\n );\n };\n\n return (\n <Dialog\n onOpenChange={(isOpen): void => {\n if (!isOpen) {\n onClose();\n }\n }}\n open={open}\n >\n <DialogContent className=\"sm:max-w-md\">\n <DialogHeader>\n <DialogTitle className=\"flex items-center gap-2\">\n Add custom connector\n <Badge\n className=\"rounded-sm px-1 py-0 text-[10px] uppercase\"\n variant=\"secondary\"\n >\n Beta\n </Badge>\n </DialogTitle>\n <DialogDescription>\n Connect {appName} to your data and tools. Learn more about\n connectors or get started with pre-built ones.\n </DialogDescription>\n </DialogHeader>\n\n <FieldGroup>\n <form\n className=\"flex flex-col gap-4\"\n\n onSubmit={(event: ReadonlyFormEvent) => {\n startEventAction(async () => {\n try {\n await form.handleSubmit(handleSubmit)(event);\n } catch (error) {\n toast.error(\n error instanceof Error\n ? error.message\n : \"Failed to add connector\"\n );\n }\n });\n }}\n >\n <Controller\n control={form.control}\n name=\"name\"\n render={({ field, fieldState }) => (\n <Field data-invalid={fieldState.invalid}>\n <FieldLabel htmlFor={field.name}>Name</FieldLabel>\n\n <Input\n id={field.name}\n aria-invalid={fieldState.invalid}\n {...field}\n maxLength={MCP_NAME_MAX_LENGTH}\n placeholder=\"Name\"\n />\n\n <FieldError errors={[fieldState.error]} />\n </Field>\n )}\n />\n\n <Controller\n control={form.control}\n name=\"url\"\n render={({ field, fieldState }) => (\n <Field data-invalid={fieldState.invalid}>\n <FieldLabel htmlFor={field.name}>URL</FieldLabel>\n\n <Input\n id={field.name}\n aria-invalid={fieldState.invalid}\n {...field}\n placeholder=\"Remote MCP server URL\"\n type=\"url\"\n />\n\n <FieldError errors={[fieldState.error]} />\n </Field>\n )}\n />\n\n <Collapsible onOpenChange={setAdvancedOpen} open={advancedOpen}>\n <CollapsibleTrigger\n render={\n <Button\n className=\"text-muted-foreground hover:text-foreground h-auto p-0 hover:bg-transparent\"\n size=\"sm\"\n type=\"button\"\n variant=\"ghost\"\n >\n <ChevronDown\n className={`mr-1.5 size-4 transition-transform ${advancedOpen ? \"\" : \"-rotate-90\"}`}\n />\n Advanced settings\n </Button>\n }\n />\n <CollapsibleContent className=\"space-y-4 pt-2\">\n <Controller\n control={form.control}\n name=\"type\"\n render={({ field, fieldState }) => (\n <Field data-invalid={fieldState.invalid}>\n <FieldLabel htmlFor={field.name}>\n Transport Type\n </FieldLabel>\n\n <Select\n items={{\n http: \"HTTP (Streamable)\",\n sse: \"SSE (Server-Sent Events)\",\n }}\n onValueChange={(value): void => {\n if (value !== null) {\n field.onChange(value);\n }\n }}\n value={field.value}\n >\n <SelectTrigger\n id={field.name}\n aria-invalid={fieldState.invalid}\n onBlur={() => {\n field.onBlur();\n }}\n ref={field.ref}\n >\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectGroup>\n <SelectItem value=\"http\">\n HTTP (Streamable)\n </SelectItem>\n <SelectItem value=\"sse\">\n SSE (Server-Sent Events)\n </SelectItem>\n </SelectGroup>\n </SelectContent>\n </Select>\n\n <FieldError errors={[fieldState.error]} />\n </Field>\n )}\n />\n <Controller\n control={form.control}\n name=\"oauthClientId\"\n render={({ field, fieldState }) => (\n <Field data-invalid={fieldState.invalid}>\n <FieldLabel htmlFor={field.name}>\n OAuth Client ID (optional)\n </FieldLabel>\n\n <Input\n id={field.name}\n aria-invalid={fieldState.invalid}\n {...field}\n placeholder=\"Enter client ID\"\n />\n\n <FieldError errors={[fieldState.error]} />\n </Field>\n )}\n />\n <Controller\n control={form.control}\n name=\"oauthClientSecret\"\n render={({ field, fieldState }) => (\n <Field data-invalid={fieldState.invalid}>\n <FieldLabel htmlFor={field.name}>\n OAuth Client Secret (optional)\n </FieldLabel>\n\n <Input\n id={field.name}\n aria-invalid={fieldState.invalid}\n {...field}\n placeholder=\"Enter client secret\"\n type=\"password\"\n />\n\n <FieldError errors={[fieldState.error]} />\n </Field>\n )}\n />\n </CollapsibleContent>\n </Collapsible>\n\n <p className=\"text-muted-foreground text-xs leading-relaxed\">\n Only use connectors from developers you trust. {appName} does not\n control which tools developers make available and cannot verify\n that they will work as intended or that they won't change.\n </p>\n\n <DialogFooter>\n <Button\n disabled={isPending}\n onClick={onClose}\n type=\"button\"\n variant=\"outline\"\n >\n Cancel\n </Button>\n <Button disabled={isPending} type=\"submit\">\n {isPending && <Spinner />}\n Add\n </Button>\n </DialogFooter>\n </form>\n </FieldGroup>\n </DialogContent>\n </Dialog>\n );\n};\n",
|
|
91
|
+
"type": "registry:file",
|
|
92
|
+
"target": "~/plugins/mcp/ui/mcp-create-dialog.tsx"
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
"path": "src/plugins/mcp/src/ui/mcp-details-page.tsx",
|
|
96
|
+
"content": "\"use client\";\n\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport {\n AlertCircle,\n BookText,\n ChevronLeft,\n FileText,\n Loader2,\n Trash2,\n Wrench,\n} from \"lucide-react\";\nimport { useRouter, useSearchParams } from \"next/navigation\";\nimport React, { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { toast } from \"sonner\";\n\nimport { InternalLink } from \"@/components/internal-link\";\nimport { ConnectorHeader } from \"@/plugins/mcp/ui/connector-header\";\nimport { McpConnectDialog } from \"@/plugins/mcp/ui/mcp-connect-dialog\";\nimport { SettingsPageContent } from \"@/components/settings/settings-page\";\nimport { Button, buttonVariants } from \"@/components/ui/button\";\nimport { Label } from \"@/components/ui/label\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { ScrollArea } from \"@/components/ui/scroll-area\";\nimport { Separator } from \"@/components/ui/separator\";\nimport { Switch } from \"@/components/ui/switch\";\nimport { useTRPC } from \"@/trpc/react\";\n\nconst HTTP_STATUS_REGEX = /HTTP (?<status>\\d{3})/u;\n\nconst formatMcpError = (message: string): string => {\n const httpMatch = HTTP_STATUS_REGEX.exec(message);\n if (httpMatch) {\n const [, status] = httpMatch;\n if (status === \"502\") {\n return \"MCP server is temporarily unavailable (502 Bad Gateway)\";\n }\n if (status === \"503\") {\n return \"MCP server is temporarily unavailable (503 Service Unavailable)\";\n }\n if (status === \"504\") {\n return \"MCP server timed out (504 Gateway Timeout)\";\n }\n if (status === \"500\") {\n return \"MCP server encountered an internal error (500)\";\n }\n if (status === \"401\" || status === \"403\") {\n return \"Authentication failed. Try reconnecting.\";\n }\n return `MCP server returned HTTP ${status}`;\n }\n if (message.length > 200) {\n return `${message.slice(0, 200)}...`;\n }\n return message;\n};\n\nconst DetailsSection = ({\n title,\n icon,\n items,\n}: {\n readonly title: string;\n readonly icon: ReadonlyNativeSurface<React.ReactNode>;\n readonly items: readonly { readonly name: string; readonly key: string }[];\n}): React.JSX.Element => {\n const count = items.length;\n\n return (\n <div className=\"bg-card rounded-lg border p-3\">\n <div className=\"flex items-center gap-2\">\n <div className=\"text-muted-foreground\">{icon}</div>\n <span className=\"text-sm font-medium\">{title}</span>\n <span className=\"text-muted-foreground text-xs\">({count})</span>\n </div>\n <Separator className=\"my-3\" />\n {count === 0 ? (\n <p className=\"text-muted-foreground text-xs italic\">None available</p>\n ) : (\n <div className=\"flex flex-wrap gap-1.5\">\n {items.map(({ name, key }) => (\n <span\n className=\"bg-muted rounded-md px-2 py-1 font-mono text-xs\"\n key={key}\n title={name}\n >\n {name}\n </span>\n ))}\n </div>\n )}\n </div>\n );\n};\n\nconst DiscoveryContent = ({\n isLoading,\n showConnectButton,\n onConnect,\n isIncompatible,\n connectionError,\n discoveryError,\n needsOAuth,\n showDiscovery,\n discovery,\n}: {\n readonly isLoading: boolean;\n readonly showConnectButton: boolean;\n readonly onConnect: () => void;\n readonly isIncompatible: boolean;\n readonly connectionError?: string;\n readonly discoveryError: { readonly message: string } | null;\n readonly needsOAuth: boolean;\n readonly showDiscovery: boolean;\n readonly discovery: {\n readonly tools: readonly { readonly name: string }[];\n readonly resources: readonly {\n readonly name: string;\n readonly uri: string;\n }[];\n readonly prompts: readonly { readonly name: string }[];\n } | null;\n}): React.JSX.Element | null => {\n if (isLoading) {\n return (\n <div className=\"flex items-center justify-center py-12\">\n <Loader2 className=\"text-muted-foreground size-6 animate-spin\" />\n </div>\n );\n }\n\n if (showConnectButton) {\n return (\n <div className=\"flex flex-col items-center gap-4 py-12 text-center\">\n <p className=\"text-sm font-medium\">Authorization required</p>\n <p className=\"text-muted-foreground max-w-xs text-xs\">\n Connect this connector to access its tools and resources.\n </p>\n <Button onClick={onConnect}>Connect</Button>\n </div>\n );\n }\n\n if (isIncompatible) {\n return (\n <div className=\"flex flex-col items-center gap-2 py-12 text-center\">\n <AlertCircle className=\"text-destructive size-6\" />\n <p className=\"text-sm font-medium\">Incompatible server</p>\n <p className=\"text-muted-foreground max-w-xs text-xs\">\n {connectionError ??\n \"This server requires pre-configured OAuth credentials.\"}\n </p>\n </div>\n );\n }\n\n if (discoveryError && !needsOAuth) {\n return (\n <div className=\"flex flex-col items-center gap-2 py-12 text-center\">\n <AlertCircle className=\"text-destructive size-6\" />\n <p className=\"text-muted-foreground text-sm\">\n Failed to connect to MCP server\n </p>\n <p className=\"text-muted-foreground max-w-xs text-xs\">\n {formatMcpError(discoveryError.message)}\n </p>\n </div>\n );\n }\n\n if (showDiscovery && discovery) {\n return (\n <ScrollArea className=\"max-h-[60vh]\">\n <div className=\"space-y-4\">\n <DetailsSection\n icon={<Wrench className=\"size-4\" />}\n items={discovery.tools.map((tool) => ({\n key: tool.name,\n name: tool.name,\n }))}\n title=\"Tools\"\n />\n <DetailsSection\n icon={<FileText className=\"size-4\" />}\n items={discovery.resources.map((resource) => ({\n key: resource.uri,\n name: resource.name,\n }))}\n title=\"Resources\"\n />\n <DetailsSection\n icon={<BookText className=\"size-4\" />}\n items={discovery.prompts.map((prompt) => ({\n key: prompt.name,\n name: prompt.name,\n }))}\n title=\"Prompts\"\n />\n </div>\n </ScrollArea>\n );\n }\n\n return null;\n};\n\nexport const McpDetailsPage = ({\n connectorId,\n}: {\n readonly connectorId: string;\n}): React.JSX.Element => {\n const trpc = useTRPC();\n const queryClient = useQueryClient();\n const router = useRouter();\n const searchParams = useSearchParams();\n\n const [connectOpen, setConnectOpen] = useState(false);\n\n const queryKey = trpc.mcp.list.queryKey();\n\n const {\n data: connectors,\n isLoading: isLoadingConnectors,\n error: connectorsError,\n refetch: refetchConnectors,\n } = useQuery(trpc.mcp.list.queryOptions());\n\n const connector = useMemo(\n () =>\n connectors?.find(\n (candidateConnector: { readonly id: string }): boolean =>\n candidateConnector.id === connectorId\n ) ?? null,\n [connectors, connectorId]\n );\n\n const canEdit = connector?.userId !== null;\n\n const { mutate: toggleEnabled } = useMutation(\n trpc.mcp.toggleEnabled.mutationOptions({\n onError: (\n _err: unknown,\n _newData,\n context: { readonly prev: typeof connectors } | undefined\n ): void => {\n queryClient.setQueryData(queryKey, context?.prev);\n toast.error(\"Failed to update connector\");\n },\n onMutate: async (newData) => {\n await queryClient.cancelQueries({ queryKey });\n const prev = queryClient.getQueryData(queryKey);\n queryClient.setQueryData(\n queryKey,\n (old: ReadonlyNativeSurface<typeof connectors>) => {\n if (!old) {\n return old;\n }\n return old.map(\n (\n candidateConnector: ReadonlyNativeSurface<\n NonNullable<typeof connectors>[number]\n >\n ) => {\n if (candidateConnector.id === newData.id) {\n return { ...candidateConnector, enabled: newData.enabled };\n }\n return candidateConnector;\n }\n );\n }\n );\n return { prev };\n },\n onSettled: (): void => {\n void queryClient.invalidateQueries({ queryKey });\n },\n })\n );\n const { mutate: updateApproval, isPending: isUpdatingApproval } = useMutation(\n trpc.mcp.update.mutationOptions({\n onError: (): void => {\n toast.error(\"Failed to update approval setting\");\n },\n onSuccess: async (): Promise<void> => {\n await queryClient.invalidateQueries({ queryKey });\n },\n })\n );\n const { mutate: deleteConnector } = useMutation(\n trpc.mcp.delete.mutationOptions({\n onError: (\n _err: unknown,\n _data,\n context: { readonly prev: typeof connectors } | undefined\n ): void => {\n queryClient.setQueryData(queryKey, context?.prev);\n toast.error(\"Failed to uninstall connector\");\n },\n onMutate: async (data) => {\n await queryClient.cancelQueries({ queryKey });\n const prev = queryClient.getQueryData(queryKey);\n queryClient.setQueryData(\n queryKey,\n (old: ReadonlyNativeSurface<typeof connectors>) => {\n if (!old) {\n return old;\n }\n return old.filter(\n (candidateConnector: { readonly id: string }): boolean =>\n candidateConnector.id !== data.id\n );\n }\n );\n return { prev };\n },\n onSettled: (): void => {\n void queryClient.invalidateQueries({ queryKey });\n },\n onSuccess: (): void => {\n void queryClient.invalidateQueries({\n queryKey: trpc.mcp.listConnected.queryKey(),\n });\n toast.success(\"Connector uninstalled\");\n router.push(\"/settings/connectors\");\n },\n })\n );\n const {\n data: discovery,\n isLoading: isLoadingDiscovery,\n error: discoveryError,\n refetch: refetchDiscovery,\n } = useQuery({\n ...trpc.mcp.discover.queryOptions({ id: connectorId }),\n enabled: connector !== null,\n retry: false,\n });\n\n const { data: connectionStatus } = useQuery({\n ...trpc.mcp.testConnection.queryOptions({ id: connectorId }),\n enabled: connector !== null,\n retry: false,\n staleTime: 30_000,\n });\n\n const isIncompatible = connectionStatus?.status === \"incompatible\";\n\n const needsOAuth =\n discoveryError?.data?.code === \"UNAUTHORIZED\" &&\n discoveryError.message.includes(\"OAuth authorization\");\n\n useEffect((): void => {\n const connected = searchParams.get(\"connected\");\n const err = searchParams.get(\"error\");\n\n if (typeof connected === \"string\" && connected !== \"\") {\n toast.success(\"Authorization successful\");\n }\n if (typeof err === \"string\" && err !== \"\") {\n toast.error(err);\n }\n\n if (\n (typeof connected === \"string\" && connected !== \"\") ||\n (typeof err === \"string\" && err !== \"\")\n ) {\n router.replace(`/settings/connectors/${connectorId}`);\n void queryClient.invalidateQueries({\n queryKey: trpc.mcp.checkAuth.queryKey({ id: connectorId }),\n });\n void queryClient.invalidateQueries({\n queryKey: trpc.mcp.discover.queryKey({ id: connectorId }),\n });\n void refetchDiscovery();\n }\n }, [\n connectorId,\n queryClient,\n refetchDiscovery,\n router,\n searchParams,\n trpc.mcp.checkAuth,\n trpc.mcp.discover,\n ]);\n\n const handleToggleEnabled = useCallback(\n (enabled: boolean): void => {\n if (!connector) {\n return;\n }\n toggleEnabled({\n enabled,\n id: connector.id,\n });\n },\n [connector, toggleEnabled]\n );\n\n const handleApprovalChange = useCallback(\n (requireApproval: boolean): void => {\n if (!connector || !canEdit) {\n return;\n }\n updateApproval({ id: connector.id, updates: { requireApproval } });\n },\n [canEdit, connector, updateApproval]\n );\n\n const handleUninstall = useCallback((): void => {\n if (!connector) {\n return;\n }\n deleteConnector({ id: connector.id });\n }, [connector, deleteConnector]);\n\n if (isLoadingConnectors) {\n return (\n <SettingsPageContent className=\"gap-4\">\n <div className=\"animate-pulse space-y-3\">\n {[1, 2].map((placeholderIndex) => (\n <div\n className=\"bg-muted/50 h-20 rounded-lg\"\n key={placeholderIndex}\n />\n ))}\n </div>\n </SettingsPageContent>\n );\n }\n\n if (connectorsError && !connectors) {\n return (\n <SettingsPageContent className=\"gap-4\">\n <div\n role=\"alert\"\n className=\"flex flex-col items-center justify-center py-12 text-center\"\n >\n <p className=\"text-sm font-medium\">Could not load connectors</p>\n <p className=\"text-muted-foreground mt-1 text-xs\">\n {connectorsError.message}\n </p>\n {}\n <Button\n onClick={(): void => {\n void refetchConnectors();\n }}\n variant=\"outline\"\n >\n Retry\n </Button>\n </div>\n </SettingsPageContent>\n );\n }\n\n if (!connector) {\n return (\n <SettingsPageContent className=\"gap-4\">\n <InternalLink\n href=\"/settings/connectors\"\n className={buttonVariants({\n className: \"w-fit\",\n size: \"sm\",\n variant: \"ghost\",\n })}\n >\n <ChevronLeft className=\"size-4\" />\n Back\n </InternalLink>\n <div className=\"flex flex-col items-center justify-center py-12 text-center\">\n <AlertCircle className=\"text-destructive size-6\" />\n <p className=\"mt-2 text-sm font-medium\">Connector not found</p>\n <p className=\"text-muted-foreground mt-1 text-xs\">\n It may have been deleted or you don’t have access.\n </p>\n </div>\n </SettingsPageContent>\n );\n }\n\n const showConnectButton = needsOAuth && !isIncompatible;\n const showDiscovery = Boolean(discovery) && !needsOAuth && !isIncompatible;\n\n return (\n <SettingsPageContent className=\"gap-4\">\n <InternalLink\n href=\"/settings/connectors\"\n className={buttonVariants({\n className: \"w-fit\",\n size: \"sm\",\n variant: \"ghost\",\n })}\n >\n <ChevronLeft className=\"size-4\" />\n Back\n </InternalLink>\n\n <div className=\"flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between\">\n <ConnectorHeader\n isCustom={connector.userId !== null}\n name={connector.name}\n type={connector.type}\n url={connector.url}\n />\n\n <div className=\"flex shrink-0 items-center gap-6\">\n <div className=\"flex items-center gap-2\">\n <Switch\n checked={connector.enabled}\n disabled={!canEdit}\n id=\"connector-enabled\"\n onCheckedChange={handleToggleEnabled}\n />\n <Label\n className=\"text-muted-foreground text-xs\"\n htmlFor=\"connector-enabled\"\n >\n Enabled\n </Label>\n </div>\n\n {canEdit ? (\n <Button onClick={handleUninstall} size=\"sm\" variant=\"destructive\">\n <Trash2 className=\"size-4\" />\n Uninstall\n </Button>\n ) : null}\n </div>\n </div>\n\n <div className=\"flex items-center justify-between gap-4 rounded-lg border p-4\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"connector-require-approval\">Require approval</Label>\n <p\n className=\"text-muted-foreground text-sm\"\n id=\"connector-approval-description\"\n >\n Ask before running tools from this connection.\n </p>\n </div>\n <Switch\n aria-describedby=\"connector-approval-description\"\n checked={connector.requireApproval}\n disabled={!canEdit || isUpdatingApproval}\n id=\"connector-require-approval\"\n onCheckedChange={handleApprovalChange}\n />\n </div>\n\n <Separator className=\"my-2\" />\n\n <DiscoveryContent\n connectionError={connectionStatus?.error}\n discovery={discovery ?? null}\n discoveryError={discoveryError}\n isIncompatible={isIncompatible}\n isLoading={isLoadingDiscovery}\n needsOAuth={needsOAuth}\n onConnect={(): void => {\n setConnectOpen(true);\n }}\n showConnectButton={showConnectButton}\n showDiscovery={showDiscovery}\n />\n\n <McpConnectDialog\n connector={connector}\n onClose={(): void => {\n setConnectOpen(false);\n }}\n open={connectOpen}\n />\n </SettingsPageContent>\n );\n};\n",
|
|
97
|
+
"type": "registry:file",
|
|
98
|
+
"target": "~/plugins/mcp/ui/mcp-details-page.tsx"
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
"path": "src/plugins/mcp/src/composer.tsx",
|
|
102
|
+
"content": "\"use client\";\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { Plug, Settings } from \"lucide-react\";\nimport type { ComposerControlProps } from \"@/components/composer/control\";\nimport React from \"react\";\nimport { toast } from \"sonner\";\n\nimport { InternalLink } from \"@/components/internal-link\";\n\nimport {\n DropdownMenuCheckboxItem,\n DropdownMenuGroup,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuSeparator,\n DropdownMenuSub,\n DropdownMenuSubContent,\n DropdownMenuSubTrigger,\n} from \"@/components/ui/dropdown-menu\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { installedPlugins } from \"@/composition/generated/installed\";\nimport { useSession } from \"@/providers/session-provider\";\nimport { useTRPC } from \"@/trpc/react\";\n\nconst ConnectorsControl = ({\n disabled,\n}: ComposerControlProps): React.JSX.Element | null => {\n const trpc = useTRPC();\n const queryClient = useQueryClient();\n\n const { data: session } = useSession();\n const isAuthenticated = Boolean(session?.user);\n\n const {\n data: connectors,\n isPending,\n isError,\n } = useQuery({\n ...trpc.mcp.listConnected.queryOptions(),\n enabled: installedPlugins.has(\"mcp\") && isAuthenticated,\n });\n\n const queryKey = trpc.mcp.listConnected.queryKey();\n\n const { mutate: toggleEnabled } = useMutation(\n trpc.mcp.toggleEnabled.mutationOptions({\n onError: (\n _err: unknown,\n _newData,\n context: { readonly prev: typeof connectors } | undefined\n ): void => {\n queryClient.setQueryData(queryKey, context?.prev);\n toast.error(\"Failed to update connector\");\n },\n onMutate: async (newData) => {\n await queryClient.cancelQueries({ queryKey });\n const prev = queryClient.getQueryData(queryKey);\n queryClient.setQueryData(\n queryKey,\n (old: ReadonlyNativeSurface<typeof connectors>) => {\n if (!old) {\n return old;\n }\n return old.map(\n (\n connector: ReadonlyNativeSurface<\n NonNullable<typeof connectors>[number]\n >\n ) => {\n if (connector.id === newData.id) {\n return { ...connector, enabled: newData.enabled };\n }\n return connector;\n }\n );\n }\n );\n return { prev };\n },\n onSettled: (): void => {\n void queryClient.invalidateQueries({ queryKey });\n },\n })\n );\n if (!installedPlugins.has(\"mcp\")) {\n return null;\n }\n let status: string | undefined;\n if (!isAuthenticated) {\n status = \"Sign in to use connectors\";\n } else if (isPending) {\n status = \"Loading connectors…\";\n } else if (isError) {\n status = \"Could not load connectors\";\n } else if (!connectors?.length) {\n status = \"No connected servers\";\n }\n return (\n <DropdownMenuSub>\n <DropdownMenuSubTrigger disabled={disabled}>\n <Plug />\n Connectors\n </DropdownMenuSubTrigger>\n <DropdownMenuSubContent className=\"w-56\">\n <DropdownMenuGroup>\n {typeof status === \"string\" && status !== \"\" ? (\n <DropdownMenuLabel>{status}</DropdownMenuLabel>\n ) : (\n connectors?.map(\n (connector: {\n readonly id: string;\n readonly enabled: boolean;\n readonly userId: string | null;\n readonly name: string;\n }) => (\n <DropdownMenuCheckboxItem\n key={connector.id}\n checked={connector.enabled}\n disabled={disabled === true || connector.userId === null}\n closeOnClick={false}\n onCheckedChange={(\n enabled: boolean | \"indeterminate\"\n ): void => {\n toggleEnabled({\n enabled: enabled === true,\n id: connector.id,\n });\n }}\n >\n <span className=\"truncate\">{connector.name}</span>\n </DropdownMenuCheckboxItem>\n )\n )\n )}\n <DropdownMenuSeparator />\n <DropdownMenuItem\n render={\n <InternalLink\n href={isAuthenticated ? \"/settings/connectors\" : \"/login\"}\n />\n }\n >\n <Settings />\n {isAuthenticated ? \"Manage connectors\" : \"Sign in\"}\n </DropdownMenuItem>\n </DropdownMenuGroup>\n </DropdownMenuSubContent>\n </DropdownMenuSub>\n );\n};\n\nConnectorsControl.isAvailable = (): boolean => installedPlugins.has(\"mcp\");\nexport { ConnectorsControl };\n",
|
|
103
|
+
"type": "registry:file",
|
|
104
|
+
"target": "~/plugins/mcp/composer.tsx"
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
"path": "src/plugins/mcp/src/db/mcp-schema.ts",
|
|
108
|
+
"content": "import type { InferSelectModel } from \"drizzle-orm\";\nimport {\n boolean,\n index,\n pgTable,\n text,\n timestamp,\n uniqueIndex,\n uuid,\n varchar,\n} from \"drizzle-orm/pg-core\";\nimport { user } from \"@/lib/db/schema\";\nimport { encryptedJson, encryptedText } from \"./encrypted-text\";\n\nconst mcpConnector = pgTable(\n \"McpConnector\",\n {\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n enabled: boolean(\"enabled\").notNull().default(true),\n id: uuid(\"id\").primaryKey().notNull().defaultRandom(),\n name: varchar(\"name\", { length: 256 }).notNull(),\n // Unique per user, used as namespace for tool IDs.\n nameId: varchar(\"nameId\", { length: 256 }).notNull(),\n oauthClientId: text(\"oauthClientId\"),\n oauthClientSecret: encryptedText(\"oauthClientSecret\"),\n requireApproval: boolean(\"requireApproval\").notNull().default(false),\n type: varchar(\"type\", { enum: [\"http\", \"sse\"] })\n .notNull()\n .default(\"http\"),\n updatedAt: timestamp(\"updatedAt\")\n .notNull()\n .defaultNow()\n .$onUpdate(() => new Date()),\n url: encryptedText(\"url\").notNull(),\n // Null = global.\n userId: text(\"userId\").references(() => user.id, { onDelete: \"cascade\" }),\n },\n (columns) => [\n index(\"McpConnector_user_id_idx\").on(columns.userId),\n index(\"McpConnector_user_name_id_idx\").on(columns.userId, columns.nameId),\n uniqueIndex(\"McpConnector_user_name_id_unique\").on(\n columns.userId,\n columns.nameId\n ),\n ]\n);\n\ntype McpConnector = InferSelectModel<typeof mcpConnector>;\n\nconst mcpOAuthSession = pgTable(\n \"McpOAuthSession\",\n {\n // OAuthClientInformationFull from MCP SDK.\n clientInfo: encryptedJson(\"clientInfo\"),\n // PKCE verifier.\n codeVerifier: encryptedText(\"codeVerifier\"),\n createdAt: timestamp(\"createdAt\").notNull().defaultNow(),\n id: uuid(\"id\").primaryKey().notNull().defaultRandom(),\n mcpConnectorId: uuid(\"mcpConnectorId\")\n .notNull()\n .references(() => mcpConnector.id, { onDelete: \"cascade\" }),\n serverUrl: text(\"serverUrl\").notNull(),\n // OAuth state parameter, unique for security.\n state: text(\"state\").unique(),\n // OAuthTokens from MCP SDK.\n tokens: encryptedJson(\"tokens\"),\n updatedAt: timestamp(\"updatedAt\")\n .notNull()\n .defaultNow()\n .$onUpdate(() => new Date()),\n },\n (columns) => [\n index(\"McpOAuthSession_connector_idx\").on(columns.mcpConnectorId),\n index(\"McpOAuthSession_state_idx\").on(columns.state),\n ]\n);\n\ntype McpOAuthSession = InferSelectModel<typeof mcpOAuthSession>;\n\nexport { mcpConnector, mcpOAuthSession };\nexport type { McpConnector, McpOAuthSession };\n",
|
|
109
|
+
"type": "registry:file",
|
|
110
|
+
"target": "~/plugins/mcp/db/mcp-schema.ts"
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
"path": "src/plugins/mcp/src/db/encrypted-text.ts",
|
|
114
|
+
"content": "import { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\n\nimport { customType } from \"drizzle-orm/pg-core\";\n\nimport { readMcpEncryptionKey } from \"@/plugins/mcp/mcp-env\";\n\nconst isJsonObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst ALGORITHM = \"aes-256-gcm\";\nconst AES_GCM_IV_BYTE_LENGTH = 16;\n\nconst getKey = (): Buffer => {\n const key = readMcpEncryptionKey();\n if (typeof key !== \"string\" || key === \"\") {\n throw new Error(\"MCP_ENCRYPTION_KEY is not configured\");\n }\n return Buffer.from(key, \"base64\");\n};\n\nconst encrypt = (plaintext: string): string => {\n const key = getKey();\n const iv = randomBytes(AES_GCM_IV_BYTE_LENGTH);\n const cipher = createCipheriv(ALGORITHM, key, iv);\n const encrypted = Buffer.concat([\n cipher.update(plaintext, \"utf-8\"),\n cipher.final(),\n ]);\n const authTag = cipher.getAuthTag();\n return `${iv.toString(\"base64\")}:${authTag.toString(\"base64\")}:${encrypted.toString(\"base64\")}`;\n};\nconst decrypt = (encrypted: string): string => {\n const key = getKey();\n const [ivB64, authTagB64, dataB64] = encrypted.split(\":\");\n if (!(ivB64 && authTagB64 && dataB64)) {\n throw new Error(\"Invalid encrypted text format\");\n }\n const decipher = createDecipheriv(\n ALGORITHM,\n key,\n Buffer.from(ivB64, \"base64\")\n );\n decipher.setAuthTag(Buffer.from(authTagB64, \"base64\"));\n return decipher.update(dataB64, \"base64\", \"utf-8\") + decipher.final(\"utf-8\");\n};\n\n/**\n * Custom Drizzle type for encrypted text fields.\n * Automatically encrypts on write and decrypts on read using AES-256-GCM.\n */\nconst encryptedText = customType<{ driverData: string; data: string }>({\n dataType: (): string => \"text\",\n fromDriver: (value): string => decrypt(value),\n toDriver: (value): string => encrypt(value),\n});\n\n/**\n * Custom Drizzle type for encrypted JSON fields.\n * Automatically encrypts on write and decrypts on read using AES-256-GCM.\n * Stores JSON objects as encrypted text in the database.\n * @returns {ReturnType<typeof customType<{ driverData: string; data: Record<string, unknown> }>>} Native column factory that encrypts serialized objects and validates decrypted JSON as an object.\n */\nconst encryptedJson = customType<{\n driverData: string;\n data: Record<string, unknown>;\n}>({\n dataType: (): string => \"text\",\n fromDriver: (value): Record<string, unknown> => {\n const parsed: unknown = JSON.parse(decrypt(value));\n if (!isJsonObject(parsed)) {\n throw new TypeError(\"Encrypted JSON column must contain an object.\");\n }\n return parsed;\n },\n toDriver: (value: Readonly<Record<string, unknown>>): string =>\n encrypt(JSON.stringify(value)),\n});\nexport { encryptedJson, encryptedText };\n",
|
|
115
|
+
"type": "registry:file",
|
|
116
|
+
"target": "~/plugins/mcp/db/encrypted-text.ts"
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
"path": "src/plugins/mcp/src/mcp-env.ts",
|
|
120
|
+
"content": "const ENCRYPTION_KEY_BYTES = 32;\nconst KEY_FORMAT_MESSAGE = \"MCP_ENCRYPTION_KEY must encode a 32-byte key.\";\n\nconst isValidEncryptionKey = (key: string | undefined): key is string => {\n if (key === undefined) {\n return false;\n }\n const decoded = Buffer.from(key, \"base64\");\n return (\n decoded.length === ENCRYPTION_KEY_BYTES &&\n decoded.toString(\"base64\") === key\n );\n};\n\nconst validateEnvironment = (env: Readonly<NodeJS.ProcessEnv>): string[] =>\n isValidEncryptionKey(env.MCP_ENCRYPTION_KEY) ? [] : [KEY_FORMAT_MESSAGE];\n\n/** Read only when encrypting/decrypting; schema generation needs no credentials. */\nconst readMcpEncryptionKey = (): string => {\n const key = process.env.MCP_ENCRYPTION_KEY;\n if (!isValidEncryptionKey(key)) {\n throw new Error(KEY_FORMAT_MESSAGE);\n }\n return key;\n};\nexport { readMcpEncryptionKey, validateEnvironment };\n",
|
|
121
|
+
"type": "registry:file",
|
|
122
|
+
"target": "~/plugins/mcp/mcp-env.ts"
|
|
123
|
+
},
|
|
124
|
+
{
|
|
125
|
+
"path": "src/plugins/mcp/src/settings.ts",
|
|
126
|
+
"content": "import { Plug } from \"lucide-react\";\n\nimport type { SettingsItem } from \"@/components/settings/settings-item\";\nimport { installedPlugins } from \"@/composition/generated/installed\";\n\nexport const mcpSettingsItem: SettingsItem = {\n href: \"/settings/connectors\",\n icon: Plug,\n id: \"mcp\",\n isVisible: () => installedPlugins.has(\"mcp\"),\n label: \"Connectors\",\n};\n",
|
|
127
|
+
"type": "registry:file",
|
|
128
|
+
"target": "~/plugins/mcp/settings.ts"
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
"path": "src/plugins/mcp/src/setup.ts",
|
|
132
|
+
"content": "import descriptor from \"@/plugins/mcp/chatjs.json\";\nimport { validateEnvironment } from \"./mcp-env\";\nimport {\n MissingCredentialsError,\n requireCredentials,\n} from \"@/lib/required-credentials\";\n\nexport const requireMcpCredentials = (): void => {\n requireCredentials(\"mcp\", descriptor.envRequirements, process.env);\n if (validateEnvironment(process.env).length > 0) {\n throw new MissingCredentialsError(\"mcp\", [\n {\n options: [[\"MCP_ENCRYPTION_KEY\"]],\n description: \"A base64-encoded 32-byte key is required\",\n },\n ]);\n }\n};\n",
|
|
133
|
+
"type": "registry:file",
|
|
134
|
+
"target": "~/plugins/mcp/setup.ts"
|
|
135
|
+
},
|
|
136
|
+
{
|
|
137
|
+
"path": "src/plugins/mcp/src/oauth/cache.ts",
|
|
138
|
+
"content": "import { revalidateTag, unstable_cache } from \"next/cache\";\n\nimport { createModuleLogger } from \"@/lib/logger\";\n\nconst log = createModuleLogger(\"mcp-cache\");\n\n// Cache tags\nconst mcpCacheTags = {\n connectionStatus: (connectorId: string): string =>\n `mcp-connection-status-${connectorId}`,\n discovery: (connectorId: string): string => `mcp-discovery-${connectorId}`,\n} as const;\n\n// Types for cached results\ninterface ConnectionStatusResult {\n error?: string;\n needsAuth: boolean;\n status:\n | \"disconnected\"\n | \"connecting\"\n | \"connected\"\n | \"authorizing\"\n | \"incompatible\";\n}\n\ninterface DiscoveryResult {\n prompts: {\n name: string;\n description: string | null;\n arguments: {\n name: string;\n description: string | null;\n required: boolean;\n }[];\n }[];\n resources: {\n name: string;\n uri: string;\n description: string | null;\n mimeType: string | null;\n }[];\n tools: { name: string; description: string | null }[];\n}\n\n/**\n * Create a cached connection status fetcher for a specific connector.\n * Successful connection status is cached for 60 seconds. Failures are not cached.\n */\nclass UncachedConnectionStatusError extends Error {\n public readonly result: ConnectionStatusResult;\n\n public constructor(result: Readonly<ConnectionStatusResult>) {\n super(\"MCP connection status is unavailable\");\n this.name = \"UncachedConnectionStatusError\";\n this.result = result;\n }\n}\n\nconst createCachedConnectionStatus = (\n connectorId: string,\n fetcher: () => Promise<ConnectionStatusResult>\n): (() => Promise<ConnectionStatusResult>) => {\n const cached = unstable_cache(\n async () => {\n const result = await fetcher();\n if (\n (typeof result.error === \"string\" && result.error !== \"\") ||\n result.status !== \"connected\"\n ) {\n throw new UncachedConnectionStatusError(result);\n }\n return result;\n },\n [\"mcp-connection-status\", connectorId],\n {\n revalidate: 60,\n tags: [mcpCacheTags.connectionStatus(connectorId)],\n }\n );\n return async () => {\n try {\n return await cached();\n } catch (error) {\n if (error instanceof UncachedConnectionStatusError) {\n return error.result;\n }\n throw error;\n }\n };\n};\n\n/**\n * Create a cached discovery fetcher for a specific connector.\n * Cache duration: 5 minutes (tools/resources/prompts rarely change)\n * @param {string} connectorId - Connector whose discovery result is cached.\n * @param {() => Promise<DiscoveryResult>} fetcher - Loads discovery when the cache misses.\n * @returns {(() => Promise<DiscoveryResult>)} A cached discovery loader.\n */\nconst createCachedDiscovery = (\n connectorId: string,\n fetcher: () => Promise<DiscoveryResult>\n): (() => Promise<DiscoveryResult>) =>\n unstable_cache(\n async () => {\n log.debug({ connectorId }, \"Fetching discovery (cache miss)\");\n return await fetcher();\n },\n [\"mcp-discovery\", connectorId],\n {\n revalidate: 300,\n tags: [mcpCacheTags.discovery(connectorId)],\n }\n );\n/**\n * Invalidate connection status cache for a connector.\n * Call this on: auth errors, disconnect, OAuth completion\n * @param {string} connectorId - Connector whose cached results are invalidated.\n */\nconst invalidateConnectionStatus = (connectorId: string): void => {\n log.debug({ connectorId }, \"Invalidating connection status cache\");\n revalidateTag(mcpCacheTags.connectionStatus(connectorId), { expire: 0 });\n};\n\n/**\n * Invalidate discovery cache for a connector.\n * Call this on: disconnect, OAuth completion, refreshClient\n * @param {string} connectorId - Connector whose cached results are invalidated.\n */\nconst invalidateDiscovery = (connectorId: string): void => {\n log.debug({ connectorId }, \"Invalidating discovery cache\");\n revalidateTag(mcpCacheTags.discovery(connectorId), { expire: 0 });\n};\n\n/**\n * Invalidate all MCP caches for a connector.\n * @param {string} connectorId - Connector whose cached results are invalidated.\n */\nconst invalidateAllMcpCaches = (connectorId: string): void => {\n invalidateConnectionStatus(connectorId);\n invalidateDiscovery(connectorId);\n};\nexport {\n createCachedConnectionStatus,\n createCachedDiscovery,\n invalidateAllMcpCaches,\n};\nexport type { ConnectionStatusResult, DiscoveryResult };\n",
|
|
139
|
+
"type": "registry:file",
|
|
140
|
+
"target": "~/plugins/mcp/oauth/cache.ts"
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
"path": "src/plugins/mcp/src/oauth/mcp-client-manager.ts",
|
|
144
|
+
"content": "import { invalidateAllMcpCaches } from \"@/plugins/mcp/oauth/cache\";\nimport { MCPClient } from \"@/plugins/mcp/oauth/mcp-client\";\n\n// Map to store active MCP clients by connector ID\nconst clientsMap = new Map<string, MCPClient>();\n\n/**\n * Get or create an MCP client for a connector.\n * @param {Readonly<{ id: string; name: string; url: string; type: \"http\" | \"sse\"; headers?: Readonly<Record<string, string>>; oauthClientId?: string | null; oauthClientSecret?: string | null; }>} options - Connector identity and transport configuration.\n * @returns {MCPClient} The cached client, creating it when absent.\n */\nconst getOrCreateMcpClient = (\n options: Readonly<{\n id: string;\n name: string;\n url: string;\n type: \"http\" | \"sse\";\n headers?: Readonly<Record<string, string>>;\n oauthClientId?: string | null;\n oauthClientSecret?: string | null;\n }>\n): MCPClient => {\n const { id, name, url, type, headers, oauthClientId, oauthClientSecret } =\n options;\n let client = clientsMap.get(id);\n if (!client) {\n client = new MCPClient(\n id,\n name,\n { headers, oauthClientId, oauthClientSecret, type, url },\n () => {\n invalidateAllMcpCaches(id);\n }\n );\n clientsMap.set(id, client);\n }\n return client;\n};\n\n/**\n * Remove an MCP client from the cache and close it.\n * @param {string} id - Connector whose client should close.\n * @param {string | undefined} expectedOAuthState - When supplied, only close the matching authorizing client.\n */\nconst removeMcpClient = async (\n id: string,\n expectedOAuthState?: string\n): Promise<void> => {\n const client = clientsMap.get(id);\n if (client) {\n if (typeof expectedOAuthState === \"string\") {\n if (client.status !== \"authorizing\") {\n return;\n }\n const authorizationUrl = client.getAuthorizationUrl();\n if (\n !authorizationUrl ||\n authorizationUrl.searchParams.get(\"state\") !== expectedOAuthState\n ) {\n return;\n }\n }\n clientsMap.delete(id);\n await client.close();\n }\n};\n/**\n * Create a fresh MCP client for OAuth callback handling.\n * Does NOT use the cache - creates a new instance to avoid state conflicts.\n * @param {Readonly<{ id: string; name: string; url: string; type: \"http\" | \"sse\"; headers?: Readonly<Record<string, string>>; oauthClientId?: string | null; oauthClientSecret?: string | null; }>} options - Connector identity and transport configuration.\n * @returns {MCPClient} A fresh client independent of the active client cache.\n */\nconst createMcpClientForCallback = (\n options: Readonly<{\n id: string;\n name: string;\n url: string;\n type: \"http\" | \"sse\";\n headers?: Readonly<Record<string, string>>;\n oauthClientId?: string | null;\n oauthClientSecret?: string | null;\n }>\n): MCPClient => {\n const { id, name, url, type, headers, oauthClientId, oauthClientSecret } =\n options;\n return new MCPClient(\n id,\n name,\n { headers, oauthClientId, oauthClientSecret, type, url },\n () => {\n invalidateAllMcpCaches(id);\n }\n );\n};\nexport { createMcpClientForCallback, getOrCreateMcpClient, removeMcpClient };\n",
|
|
145
|
+
"type": "registry:file",
|
|
146
|
+
"target": "~/plugins/mcp/oauth/mcp-client-manager.ts"
|
|
147
|
+
},
|
|
148
|
+
{
|
|
149
|
+
"path": "src/plugins/mcp/src/oauth/mcp-client.ts",
|
|
150
|
+
"content": "import type {\n ListPromptsResult,\n ListResourcesResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport {\n auth,\n experimental_createMCPClient as createMCPClient,\n} from \"@ai-sdk/mcp\";\nimport { McpOAuthClientProvider } from \"@/plugins/mcp/oauth/mcp-oauth-provider\";\nimport { OAuthAuthorizationRequiredError } from \"@/plugins/mcp/oauth/oauth-authorization-required-error\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport type { Tool } from \"ai\";\nimport { config } from \"@/lib/config\";\nimport { createModuleLogger } from \"@/lib/logger\";\nimport { getBaseUrl } from \"@/lib/url\";\n\nconst log = createModuleLogger(\"mcp-client\");\n\nconst INITIAL_CONNECTION_GENERATION = 0;\nconst MCP_CONNECTION_TIMEOUT_MS = 30_000;\n\nconst getMcpErrorMessage = (error: unknown): string => {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n};\n\ntype McpPreconnect = (\n url: string | URL,\n options?: {\n readonly dns?: boolean;\n readonly http?: boolean;\n readonly https?: boolean;\n readonly tcp?: boolean;\n }\n) => void;\n\nconst isMcpPreconnect = (value: unknown): value is McpPreconnect =>\n typeof value === \"function\";\n\n// Bun's fetch type requires preconnect. Node's does not. Delegate when the\n// runtime provides it so one fetch value satisfies both FetchFunction types.\nconst mcpPreconnect: McpPreconnect = (url, options): void => {\n const candidate: object = globalThis.fetch;\n if (!(\"preconnect\" in candidate)) {\n return;\n }\n const method: unknown = candidate.preconnect;\n if (!isMcpPreconnect(method)) {\n return;\n }\n method(url, options);\n};\n\nconst toMcpSdkFetch = (\n fetchImpl: (\n ...args: Parameters<typeof globalThis.fetch>\n ) => ReturnType<typeof globalThis.fetch>\n): typeof globalThis.fetch =>\n Object.assign(fetchImpl, { preconnect: mcpPreconnect });\n\ntype McpClientInstance = Awaited<ReturnType<typeof createMCPClient>>;\n\ntype McpClientStatus =\n | \"disconnected\"\n | \"connecting\"\n | \"connected\"\n | \"authorizing\"\n | \"incompatible\";\n\n/**\n * MCP Client wrapper with OAuth support.\n * Uses @ai-sdk/mcp's createMCPClient with authProvider for OAuth flow.\n */\nexport class MCPClient {\n private client?: McpClientInstance;\n private generation = INITIAL_CONNECTION_GENERATION;\n private connectionAbort?: AbortController;\n private connectPromise?: Promise<void>;\n private readonly invalidateCache?: () => void;\n private oauthProvider: McpOAuthClientProvider;\n private authorizationUrl?: URL;\n private connectionStatus: McpClientStatus = \"disconnected\";\n\n private readonly id: string;\n private readonly name: string;\n private readonly serverConfig: {\n url: string;\n type: \"http\" | \"sse\";\n headers?: Record<string, string>;\n oauthClientId?: string | null;\n oauthClientSecret?: string | null;\n };\n\n public constructor(\n id: string,\n name: string,\n serverConfig: {\n readonly url: string;\n readonly type: \"http\" | \"sse\";\n readonly headers?: Readonly<Record<string, string>>;\n readonly oauthClientId?: string | null;\n readonly oauthClientSecret?: string | null;\n },\n invalidateCache?: () => void\n ) {\n this.invalidateCache = invalidateCache;\n this.id = id;\n this.name = name;\n this.serverConfig = serverConfig;\n this.oauthProvider = this.createOAuthProvider();\n }\n\n private createOAuthProvider(): McpOAuthClientProvider {\n const { generation } = this;\n const baseUrl = getBaseUrl();\n\n return new McpOAuthClientProvider({\n clientMetadata: {\n client_name: `${config.appPrefix}-${this.name}`,\n grant_types: [\"authorization_code\", \"refresh_token\"],\n redirect_uris: [`${baseUrl}/api/mcp/oauth/callback`],\n response_types: [\"code\"],\n scope: \"mcp:tools\",\n software_id: config.appPrefix,\n software_version: \"1.0.0\",\n token_endpoint_auth_method:\n typeof this.serverConfig.oauthClientId === \"string\" &&\n this.serverConfig.oauthClientId !== \"\" &&\n typeof this.serverConfig.oauthClientSecret === \"string\" &&\n this.serverConfig.oauthClientSecret !== \"\"\n ? \"client_secret_basic\"\n : \"none\",\n },\n mcpConnectorId: this.id,\n oauthClientId: this.serverConfig.oauthClientId,\n oauthClientSecret: this.serverConfig.oauthClientSecret,\n onRedirectToAuthorization: (\n authorizationUrl: ReadonlyNativeSurface<URL>\n ): never => {\n if (generation !== this.generation) {\n throw new Error(\"MCP connection was closed\");\n }\n this.authorizationUrl = authorizationUrl;\n throw new OAuthAuthorizationRequiredError(authorizationUrl);\n },\n serverUrl: this.serverConfig.url,\n });\n }\n\n public get status(): McpClientStatus {\n if (this.authorizationUrl) {\n return \"authorizing\";\n }\n if (this.client) {\n return \"connected\";\n }\n return this.connectionStatus;\n }\n\n public getAuthorizationUrl(): URL | undefined {\n return this.authorizationUrl;\n }\n\n public get serverInfo(): McpClientInstance[\"serverInfo\"] | undefined {\n const { client } = this;\n return client && client.serverInfo;\n }\n\n public async connect({\n oauthState,\n abortSignal,\n }: {\n readonly oauthState?: string;\n readonly abortSignal?: Readonly<\n Pick<\n AbortSignal,\n | \"throwIfAborted\"\n | \"reason\"\n | \"addEventListener\"\n | \"removeEventListener\"\n | \"aborted\"\n >\n >;\n } = {}): Promise<void> {\n if (abortSignal) {\n abortSignal.throwIfAborted();\n }\n if (!this.connectPromise) {\n const { generation } = this;\n this.connectPromise = (async (): Promise<void> => {\n try {\n await this.connectOnce(oauthState);\n } finally {\n // Only close() can retire a pending attempt and allow a replacement.\n if (this.generation === generation) {\n this.connectPromise = undefined;\n }\n }\n })();\n }\n if (!abortSignal) {\n await this.connectPromise;\n return;\n }\n const aborted = Promise.withResolvers<never>();\n const cancel = (): void => {\n aborted.reject(abortSignal.reason);\n };\n abortSignal.addEventListener(\"abort\", cancel, { once: true });\n if (abortSignal.aborted) {\n cancel();\n }\n try {\n await Promise.race([this.connectPromise, aborted.promise]);\n } finally {\n abortSignal.removeEventListener(\"abort\", cancel);\n }\n }\n private async connectOnce(oauthState?: string): Promise<void> {\n if (this.status === \"connected\" && this.client) {\n return;\n }\n\n const { generation, oauthProvider } = this;\n this.connectionAbort = new AbortController();\n const signal = AbortSignal.any([\n this.connectionAbort.signal,\n AbortSignal.timeout(MCP_CONNECTION_TIMEOUT_MS),\n ]);\n this.connectionStatus = \"connecting\";\n\n try {\n // Adopt state if provided (for callback reconciliation).\n if (typeof oauthState === \"string\" && oauthState !== \"\") {\n await oauthProvider.adoptState(oauthState);\n }\n signal.throwIfAborted();\n // AI SDK handles 401 internally and calls auth() with the provider\n const client = await createMCPClient({\n initializationOptions: { signal },\n transport: {\n authProvider: oauthProvider,\n fetch: toMcpSdkFetch(oauthProvider.fetch),\n headers: this.serverConfig.headers,\n type: this.serverConfig.type,\n url: this.serverConfig.url,\n },\n });\n\n if (generation !== this.generation || signal.aborted) {\n await client.close();\n signal.throwIfAborted();\n throw new Error(\"MCP connection was closed\");\n }\n this.client = client;\n this.authorizationUrl = undefined;\n this.connectionStatus = \"connected\";\n } catch (error) {\n if (generation !== this.generation || signal.aborted) {\n if (generation === this.generation) {\n this.authorizationUrl = undefined;\n this.connectionStatus = \"disconnected\";\n }\n throw error;\n }\n // If OAuth required error, status becomes \"authorizing\"\n if (error instanceof OAuthAuthorizationRequiredError) {\n this.connectionStatus = \"authorizing\";\n log.info(\n { authUrl: error.authorizationUrl.toString(), connectorId: this.id },\n \"OAuth authorization required\"\n );\n return;\n }\n\n this.connectionStatus = \"disconnected\";\n throw error;\n }\n }\n /**\n * Lightweight connection test - just checks if we can connect without full discovery.\n * Returns connection status without fetching tools/resources/prompts.\n * @param {Readonly<Pick<AbortSignal, \"throwIfAborted\" | \"reason\" | \"addEventListener\" | \"removeEventListener\" | \"aborted\">> | undefined} abortSignal - Cancels this caller while shared initialization continues.\n * @returns {Promise<{ status: McpClientStatus; needsAuth: boolean; error?: string; }>} The connection or authorization status.\n */\n public async attemptConnection(\n abortSignal?: Readonly<\n Pick<\n AbortSignal,\n | \"throwIfAborted\"\n | \"reason\"\n | \"addEventListener\"\n | \"removeEventListener\"\n | \"aborted\"\n >\n >\n ): Promise<{\n status: McpClientStatus;\n needsAuth: boolean;\n error?: string;\n }> {\n // If already connected, return current status\n if (this.status === \"connected\" && this.client) {\n return { needsAuth: false, status: \"connected\" };\n }\n\n // If already in authorizing state, return that\n if (this.authorizationUrl) {\n return { needsAuth: true, status: \"authorizing\" };\n }\n\n try {\n await this.connect({ abortSignal });\n // Check if OAuth is required (authorizationUrl gets set during connect)\n if (this.authorizationUrl !== undefined) {\n return { needsAuth: true, status: \"authorizing\" };\n }\n return {\n needsAuth: false,\n status: this.client ? \"connected\" : \"disconnected\",\n };\n } catch (error) {\n const errorMessage = getMcpErrorMessage(error);\n log.error(\n {\n connectorId: this.id,\n errorMessage,\n errorStack: error instanceof Error ? error.stack : undefined,\n },\n \"attemptConnection failed\"\n );\n\n // Detect incompatible server errors\n if (\n errorMessage.includes(\"does not support dynamic client registration\")\n ) {\n this.connectionStatus = \"incompatible\";\n return {\n error:\n \"Server requires pre-configured OAuth credentials (does not support dynamic client registration)\",\n needsAuth: false,\n status: \"incompatible\",\n };\n }\n\n return { error: errorMessage, needsAuth: false, status: \"disconnected\" };\n }\n }\n /**\n * Called after callback receives code to complete the OAuth flow.\n * @param {string} code - Authorization code received by the callback.\n * @param {string} state - State used to restore the verifier session.\n */\n public async finishAuth(code: string, state: string): Promise<void> {\n const { generation, oauthProvider } = this;\n // Always adopt the state from the callback to load the session with code verifier\n await oauthProvider.adoptState(state);\n\n // Use the auth function from @ai-sdk/mcp to complete the OAuth flow\n await auth(oauthProvider, {\n authorizationCode: code,\n fetchFn: toMcpSdkFetch(oauthProvider.fetch),\n serverUrl: this.serverConfig.url,\n });\n\n if (generation !== this.generation) {\n throw new Error(\"MCP connection was closed\");\n }\n this.authorizationUrl = undefined;\n // Don't set to connected - tokens are saved, next connect() will use them\n }\n /**\n * Get tools from the MCP server, already in AI SDK format.\n * @param {Parameters<McpClientInstance[\"tools\"]>} args - Native SDK schema options.\n * @returns {Promise<Record<string, Tool>>} The discovered SDK tools.\n */\n public async tools(\n ...args: Parameters<NonNullable<McpClientInstance>[\"tools\"]>\n ): Promise<Record<string, Tool>> {\n const { client } = this;\n if (!client) {\n throw new Error(\"Client not connected\");\n }\n try {\n return await client.tools(...args);\n } catch (error) {\n await this.handlePotentialAuthError(error, client);\n throw error;\n }\n }\n /**\n * List resources from the MCP server.\n * @returns {Promise<ListResourcesResult>} The native MCP resource result.\n */\n public async listResources(): Promise<ListResourcesResult> {\n const { client } = this;\n if (!client) {\n throw new Error(\"Client not connected\");\n }\n try {\n return await client.listResources();\n } catch (error) {\n await this.handlePotentialAuthError(error, client);\n throw error;\n }\n }\n /**\n * List prompts from the MCP server.\n * @returns {Promise<ListPromptsResult>} The native MCP prompt result.\n */\n public async listPrompts(): Promise<ListPromptsResult> {\n const { client } = this;\n if (!client) {\n throw new Error(\"Client not connected\");\n }\n try {\n return await client.experimental_listPrompts();\n } catch (error) {\n await this.handlePotentialAuthError(error, client);\n throw error;\n }\n }\n /**\n * Close the connection to the MCP server.\n */\n public async close(): Promise<void> {\n this.generation += 1;\n const { connectionAbort } = this;\n if (connectionAbort) {\n connectionAbort.abort(new Error(\"MCP connection was closed\"));\n }\n this.connectPromise = undefined;\n this.oauthProvider = this.createOAuthProvider();\n const { client } = this;\n this.client = undefined;\n this.authorizationUrl = undefined;\n this.connectionStatus = \"disconnected\";\n try {\n // Await even without a client to preserve cache-invalidation timing.\n await (client && client.close());\n } catch (error) {\n log.error({ connectorId: this.id, error }, \"Error closing MCP client\");\n }\n if (this.invalidateCache) {\n this.invalidateCache();\n }\n }\n /**\n * Check if an error is an auth error (401/403) and invalidate caches if so.\n * @param {unknown} error - Failure from a connected SDK operation.\n * @param {unknown} origin - Client whose failure is being handled.\n */\n private async handlePotentialAuthError(\n error: unknown,\n origin: unknown\n ): Promise<void> {\n if (this.client !== origin) {\n return;\n }\n const errorMessage = getMcpErrorMessage(error);\n const isAuthError =\n errorMessage.includes(\"401\") ||\n errorMessage.includes(\"403\") ||\n errorMessage.includes(\"Unauthorized\") ||\n errorMessage.includes(\"Forbidden\");\n\n if (isAuthError) {\n log.warn(\n { connectorId: this.id, errorMessage },\n \"Auth error detected, invalidating caches\"\n );\n await this.close();\n }\n }\n}\n",
|
|
151
|
+
"type": "registry:file",
|
|
152
|
+
"target": "~/plugins/mcp/oauth/mcp-client.ts"
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
"path": "src/plugins/mcp/src/oauth/mcp-fetch.ts",
|
|
156
|
+
"content": "import { guardedFetch } from \"guarded-fetch\";\n\ntype ReadonlyNativeSurface<Value> = Value extends\n | string\n | number\n | bigint\n | boolean\n | symbol\n | null\n | undefined\n ? Value\n : Value extends (...parameters: readonly never[]) => unknown\n ? Value\n : Value extends abstract new (...parameters: readonly never[]) => unknown\n ? Value\n : Value extends object\n ? {\n readonly [Property in keyof Value]: ReadonlyNativeSurface<\n Value[Property]\n >;\n }\n : Value;\nconst MCP_NETWORK_TIMEOUT_MS = 30_000;\n\n/** Covers transport, discovery and OAuth requests with the same network policy.\n * @param {string | ReadonlyNativeSurface<URL | Request>} input - Native URL or request to protect with the MCP network policy.\n * @param {Readonly<RequestInit> | undefined} init - Native request overrides applied by the Request constructor.\n * @returns {Promise<Response>} The response from the guarded transport.\n */\nexport const mcpFetch = async (\n input: string | ReadonlyNativeSurface<URL | Request>,\n init?: Readonly<RequestInit>\n): Promise<Response> => {\n const request = new Request(input, init);\n return await guardedFetch(request.url, {\n ...(request.body ? { body: await request.arrayBuffer() } : {}),\n headers: request.headers,\n method: request.method,\n opaqueErrors: true,\n signal: request.signal,\n timeoutMs: MCP_NETWORK_TIMEOUT_MS,\n });\n};\n",
|
|
157
|
+
"type": "registry:file",
|
|
158
|
+
"target": "~/plugins/mcp/oauth/mcp-fetch.ts"
|
|
159
|
+
},
|
|
160
|
+
{
|
|
161
|
+
"path": "src/plugins/mcp/src/oauth/mcp-oauth-provider.ts",
|
|
162
|
+
"content": "import type {\n OAuthClientMetadata,\n OAuthClientProvider,\n OAuthTokens,\n} from \"@ai-sdk/mcp\";\nimport type { McpOAuthSession } from \"@/plugins/mcp/db/mcp-schema\";\nimport type { OAuthClientInformationFull } from \"@/plugins/mcp/db/mcp-queries\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\n\nimport { mcpFetch } from \"@/plugins/mcp/oauth/mcp-fetch\";\nimport { withMcpOAuthRefreshLock } from \"@/plugins/mcp/db/mcp-oauth-lock\";\nimport {\n createOAuthSession,\n deleteSessionByState,\n getAuthenticatedSession,\n getSessionByState,\n saveTokensAndCleanup,\n setOAuthClientInfoOnceByState,\n setOAuthCodeVerifierOnceByState,\n updateSessionByState,\n} from \"@/plugins/mcp/db/mcp-queries\";\nimport { createModuleLogger } from \"@/lib/logger\";\n\nconst log = createModuleLogger(\"mcp-oauth-provider\");\nconst refreshTokensSchema = z.object({\n access_token: z.string(),\n expires_in: z.number().optional(),\n id_token: z.string().optional(),\n refresh_token: z.string().optional(),\n scope: z.string().optional(),\n token_type: z.string(),\n});\n\n// @ai-sdk/mcp does not export its runtime OAuth schemas. Match its persisted\n// fields, including optional AS pins, while retaining server extension fields.\nconst oauthUrlSchema = z\n .url()\n .refine(\n (value) =>\n URL.canParse(value) &&\n !/^(?:javascript|data|vbscript):$/u.test(new URL(value).protocol)\n );\nconst authorizationServerPinShape = {\n authorization_server: oauthUrlSchema.optional(),\n issuer: oauthUrlSchema.optional(),\n token_endpoint: oauthUrlSchema.optional(),\n};\nconst storedTokensSchema = refreshTokensSchema\n .extend(authorizationServerPinShape)\n .loose();\nconst storedClientInformationSchema = z.looseObject({\n ...authorizationServerPinShape,\n application_type: z.enum([\"native\", \"web\"]).optional(),\n client_id: z.string(),\n client_id_issued_at: z.number().optional(),\n client_name: z.string().optional(),\n client_secret: z.string().optional(),\n client_secret_expires_at: z.number().optional(),\n client_uri: oauthUrlSchema.optional(),\n contacts: z.array(z.string()).optional(),\n grant_types: z.array(z.string()).optional(),\n jwks: z.unknown().optional(),\n jwks_uri: oauthUrlSchema.optional(),\n logo_uri: oauthUrlSchema.optional(),\n policy_uri: z.string().optional(),\n redirect_uris: z.array(oauthUrlSchema),\n response_types: z.array(z.string()).optional(),\n scope: z.string().optional(),\n software_id: z.string().optional(),\n software_statement: z.string().optional(),\n software_version: z.string().optional(),\n token_endpoint_auth_method: z.string().optional(),\n tos_uri: oauthUrlSchema.optional(),\n});\n\n/**\n * PostgreSQL-backed OAuth client provider for MCP.\n * Implements the OAuthClientProvider interface from the AI SDK.\n * Persists OAuth state, PKCE verifier, client info, and tokens to the database.\n */\nexport class McpOAuthClientProvider implements OAuthClientProvider {\n private currentOAuthState = \"\";\n private cachedAuthData: McpOAuthSession | undefined;\n private initialized = false;\n private committedRefreshes = 0;\n private saveCodeVerifierPromise: Promise<void> | null = null;\n private cachedAuthorizationUrl: URL | null = null;\n private readonly config: {\n mcpConnectorId: string;\n oauthClientId?: string | null;\n oauthClientSecret?: string | null;\n serverUrl: string;\n clientMetadata: OAuthClientMetadata;\n onRedirectToAuthorization: (\n authUrl: ReadonlyNativeSurface<URL>\n ) => Promise<void>;\n // Optional: adopt existing state (for callback reconciliation)\n state?: string;\n };\n private saveClientInformationPromise: Promise<void> | null = null;\n\n public constructor(config: {\n readonly mcpConnectorId: string;\n readonly oauthClientId?: string | null;\n readonly oauthClientSecret?: string | null;\n readonly serverUrl: string;\n readonly clientMetadata: OAuthClientMetadata;\n readonly onRedirectToAuthorization: (\n authUrl: ReadonlyNativeSurface<URL>\n ) => Promise<void>;\n // Optional: adopt existing state (for callback reconciliation)\n readonly state?: string;\n }) {\n this.config = config;\n }\n\n private initializationPromise: Promise<void> | null = null;\n\n // Prevent concurrent initialization - return existing promise if in progress\n\n private async initializeOAuth(): Promise<void> {\n if (this.initializationPromise) {\n await this.initializationPromise;\n return;\n }\n\n if (this.initialized) {\n return;\n }\n\n this.initializationPromise = this.doInitializeOAuth();\n try {\n await this.initializationPromise;\n } finally {\n this.initializationPromise = null;\n }\n }\n // If state was provided (e.g., from callback), adopt it\n\n private async doInitializeOAuth(): Promise<void> {\n if (typeof this.config.state === \"string\" && this.config.state !== \"\") {\n const session = await getSessionByState({ state: this.config.state });\n if (\n session &&\n session.mcpConnectorId === this.config.mcpConnectorId &&\n session.serverUrl === this.config.serverUrl\n ) {\n this.currentOAuthState = session.state ?? \"\";\n this.cachedAuthData = session;\n this.initialized = true;\n return;\n }\n // Check for existing authenticated session\n }\n const authenticated = await getAuthenticatedSession({\n mcpConnectorId: this.config.mcpConnectorId,\n });\n if (authenticated && authenticated.serverUrl === this.config.serverUrl) {\n this.currentOAuthState = authenticated.state ?? \"\";\n this.cachedAuthData = authenticated;\n this.initialized = true;\n return;\n // Create new in-progress session\n }\n this.currentOAuthState = randomUUID();\n this.cachedAuthData = await createOAuthSession({\n mcpConnectorId: this.config.mcpConnectorId,\n serverUrl: this.config.serverUrl,\n state: this.currentOAuthState,\n });\n this.initialized = true;\n }\n private static decodeStoredCredentials<Result>(\n schema: Readonly<Pick<z.ZodType<Result>, \"safeParse\">>,\n value: unknown,\n kind: \"client information\" | \"tokens\"\n ): Result | undefined {\n if (value === null || value === undefined) {\n return undefined;\n }\n const result = schema.safeParse(value);\n if (!result.success) {\n // Do not expose secrets in validation errors or mutate another flow's state.\n throw new Error(\n `Invalid stored MCP OAuth ${kind}; reconnect this connector.`\n );\n }\n return result.data;\n }\n\n private async getAuthData(): Promise<McpOAuthSession | undefined> {\n await this.initializeOAuth();\n return this.cachedAuthData;\n }\n private async updateAuthData(\n data: Parameters<typeof updateSessionByState>[0][\"updates\"]\n ): Promise<McpOAuthSession> {\n if (!this.currentOAuthState) {\n throw new Error(\"OAuth not initialized\");\n }\n\n this.cachedAuthData = await updateSessionByState({\n state: this.currentOAuthState,\n updates: data,\n });\n\n return this.cachedAuthData;\n }\n public get redirectUrl(): string {\n return this.config.clientMetadata.redirect_uris[0];\n }\n\n public get clientMetadata(): OAuthClientMetadata {\n return this.config.clientMetadata;\n }\n\n public state(): string {\n return this.currentOAuthState;\n }\n\n public async clientInformation(): Promise<\n OAuthClientInformationFull | undefined\n > {\n const authData = await this.getAuthData();\n if (\n typeof this.config.oauthClientId === \"string\" &&\n this.config.oauthClientId !== \"\"\n ) {\n return {\n ...this.clientMetadata,\n client_id: this.config.oauthClientId,\n client_secret: this.config.oauthClientSecret ?? undefined,\n };\n }\n const clientInfo = McpOAuthClientProvider.decodeStoredCredentials(\n storedClientInformationSchema,\n (authData ?? {}).clientInfo,\n \"client information\"\n );\n // Security: if redirect URI changed and no tokens yet, invalidate\n if (\n clientInfo &&\n authData &&\n !authData.tokens &&\n clientInfo.redirect_uris[0] !== this.redirectUrl\n ) {\n log.warn(\n {\n currentRedirectUri: this.redirectUrl,\n savedRedirectUri: clientInfo.redirect_uris[0],\n state: authData.state,\n },\n \"clientInformation: redirect URI mismatch, invalidating session\"\n );\n this.resetRegistration();\n await this.initializeOAuth();\n return undefined;\n }\n return clientInfo;\n }\n // Keep other in-flight sessions intact while resetting this registration in order.\n private resetRegistration(): void {\n this.cachedAuthData = undefined;\n this.cachedAuthorizationUrl = null;\n this.initialized = false;\n this.currentOAuthState = \"\";\n this.config.state = undefined;\n }\n public async saveClientInformation(\n clientCredentials: Parameters<\n typeof setOAuthClientInfoOnceByState\n >[0][\"clientInfo\"]\n ): Promise<void> {\n if (this.saveClientInformationPromise) {\n await this.saveClientInformationPromise;\n return;\n // If we already have a client registered for this state, keep it stable.\n }\n // Some OAuth servers treat authorization codes as bound to client_id.\n\n if ((this.cachedAuthData ?? {}).clientInfo) {\n return;\n }\n this.saveClientInformationPromise = (async (): Promise<void> => {\n try {\n this.cachedAuthData = await setOAuthClientInfoOnceByState({\n clientInfo: clientCredentials,\n state: this.currentOAuthState,\n });\n } finally {\n this.saveClientInformationPromise = null;\n }\n })();\n await this.saveClientInformationPromise;\n }\n public async tokens(): Promise<OAuthTokens | undefined> {\n const authData = await this.getAuthData();\n return McpOAuthClientProvider.decodeStoredCredentials(\n storedTokensSchema,\n (authData ?? {}).tokens,\n \"tokens\"\n );\n }\n /**\n * Send SDK transport requests and serialize refresh-token rotation under the connector lock.\n * @param {string | URL | Request} input - Native request source, passed unchanged to Request.\n * @param {RequestInit} [init] - Native request options, including headers, body and cancellation.\n * @returns {Promise<Response>} Transport response after any successful token rotation is persisted.\n */\n public fetch = async (\n input: string | ReadonlyNativeSurface<URL | Request>,\n init?: RequestInit\n ): Promise<Response> => {\n const request = new Request(input, init);\n if (\n request.method !== \"POST\" ||\n !(request.headers.get(\"content-type\") ?? \"\").includes(\n \"application/x-www-form-urlencoded\"\n )\n ) {\n return await mcpFetch(request);\n }\n const params = new URLSearchParams(await request.clone().text());\n if (params.get(\"grant_type\") !== \"refresh_token\") {\n return await mcpFetch(request);\n }\n // Compare the cached fingerprint only; validate the latest credentials under\n // the lock so a stale malformed cache cannot prevent adopting a repaired row.\n const observedAccessToken = ((this.cachedAuthData ?? {}).tokens ?? {})\n .access_token;\n return await withMcpOAuthRefreshLock(\n this.config.mcpConnectorId,\n async () => {\n request.signal.throwIfAborted();\n const latest = await getSessionByState({\n state: this.currentOAuthState,\n });\n const latestTokens = McpOAuthClientProvider.decodeStoredCredentials(\n storedTokensSchema,\n (latest ?? {}).tokens,\n \"tokens\"\n );\n const refreshToken = (latestTokens ?? {}).refresh_token;\n if (\n !latestTokens ||\n typeof refreshToken !== \"string\" ||\n refreshToken === \"\" ||\n !latest ||\n latest.mcpConnectorId !== this.config.mcpConnectorId ||\n latest.serverUrl !== this.config.serverUrl\n ) {\n throw new Error(\"MCP credentials changed; reconnect this connector.\");\n }\n if (\n latestTokens.refresh_token !== params.get(\"refresh_token\") ||\n latestTokens.access_token !== observedAccessToken\n ) {\n // Another instance already rotated this credential. Return its result\n // to the SDK instead of consuming the old single-use refresh token.\n this.cachedAuthData = latest;\n this.committedRefreshes += 1;\n return Response.json(latestTokens);\n }\n const response = await mcpFetch(request, {\n signal: AbortSignal.any([\n request.signal,\n AbortSignal.timeout(30_000),\n ]),\n });\n if (!response.ok) {\n return response;\n }\n const refreshed = refreshTokensSchema.parse(\n await response.clone().json()\n );\n // A successful rotation must be committed even if the caller cancelled:\n // the previous refresh token may already be invalid at the server.\n // Preserve pinned metadata and the refresh token when it is not rotated.\n this.cachedAuthData = await saveTokensAndCleanup({\n mcpConnectorId: this.config.mcpConnectorId,\n state: this.currentOAuthState,\n tokens: { ...latestTokens, ...refreshed },\n });\n this.committedRefreshes += 1;\n return Response.json(refreshed);\n },\n request.signal\n );\n };\n public async saveTokens(tokens: OAuthTokens): Promise<void> {\n if (this.committedRefreshes > 0) {\n // Refresh was saved while holding the cross-process lock. The SDK's\n // later save must not overwrite a newer rotation from another client.\n this.committedRefreshes -= 1;\n this.cachedAuthData = await getSessionByState({\n state: this.currentOAuthState,\n });\n return;\n }\n this.cachedAuthData = await saveTokensAndCleanup({\n mcpConnectorId: this.config.mcpConnectorId,\n state: this.currentOAuthState,\n tokens,\n });\n }\n public async redirectToAuthorization(\n authorizationUrl: ReadonlyNativeSurface<URL>\n ): Promise<void> {\n // If the SDK calls redirect twice, keep the first URL stable.\n authorizationUrl.searchParams.set(\"state\", this.state());\n // Otherwise the UI might open URL #1 while the DB ended up with verifier #2.\n\n if (this.cachedAuthorizationUrl) {\n await this.config.onRedirectToAuthorization(this.cachedAuthorizationUrl);\n return;\n }\n this.cachedAuthorizationUrl = new URL(authorizationUrl.toString());\n\n await this.config.onRedirectToAuthorization(authorizationUrl);\n }\n public async saveCodeVerifier(pkceVerifier: string): Promise<void> {\n if (this.saveCodeVerifierPromise) {\n await this.saveCodeVerifierPromise;\n return;\n // Only save verifier ONCE - the AI SDK calls this multiple times\n }\n // If we already have a verifier for this session, keep it.\n // but the code_challenge is generated from the FIRST verifier.\n const existingVerifier = (this.cachedAuthData ?? {}).codeVerifier;\n\n if (typeof existingVerifier === \"string\" && existingVerifier !== \"\") {\n log.info(\n {\n state: this.currentOAuthState,\n },\n \"saveCodeVerifier: SKIPPING - verifier already exists\"\n );\n\n return;\n }\n\n log.info(\n {\n state: this.currentOAuthState,\n },\n \"saveCodeVerifier: saving first verifier\"\n // Optimistic in-memory set so a concurrent call in this instance will skip.\n );\n if (this.cachedAuthData) {\n this.cachedAuthData = {\n ...this.cachedAuthData,\n codeVerifier: pkceVerifier,\n };\n // Serialize and make the DB write immutable (DB-side also guards against overwrite).\n }\n this.saveCodeVerifierPromise = (async (): Promise<void> => {\n try {\n this.cachedAuthData = await setOAuthCodeVerifierOnceByState({\n codeVerifier: pkceVerifier,\n state: this.currentOAuthState,\n });\n } finally {\n this.saveCodeVerifierPromise = null;\n }\n })();\n await this.saveCodeVerifierPromise;\n }\n public async codeVerifier(): Promise<string> {\n const authData = await this.getAuthData();\n log.info(\n {\n hasCodeVerifier: Boolean((authData ?? {}).codeVerifier),\n state: this.currentOAuthState,\n },\n \"codeVerifier called\"\n );\n if (\n !authData ||\n typeof authData.codeVerifier !== \"string\" ||\n authData.codeVerifier === \"\"\n ) {\n throw new Error(\"OAuth code verifier not found\");\n }\n return authData.codeVerifier;\n }\n /**\n * Adopt state from another instance (multi-instance support).\n * Used when the callback needs to reconcile with an existing session.\n * @param {string} state - Candidate persisted state; absent or foreign-connector rows are ignored.\n */\n public async adoptState(state: string): Promise<void> {\n if (!state) {\n log.warn(\"adoptState called with empty state\");\n return;\n // If already initialized with this exact state, skip DB lookup\n }\n if (this.initialized && this.currentOAuthState === state) {\n log.info({ state }, \"adoptState: already initialized with this state\");\n return;\n }\n\n const session = await getSessionByState({ state });\n if (!session) {\n log.warn({ state }, \"adoptState: session not found\");\n return;\n }\n if (session.mcpConnectorId !== this.config.mcpConnectorId) {\n log.warn(\n {\n expectedConnectorId: this.config.mcpConnectorId,\n sessionConnectorId: session.mcpConnectorId,\n state,\n },\n \"adoptState: connector ID mismatch\"\n );\n return;\n }\n if (session.serverUrl !== this.config.serverUrl) {\n throw new Error(\"OAuth session belongs to a different MCP server\");\n }\n log.info(\n {\n hasClientInfo: Boolean(session.clientInfo),\n hasCodeVerifier: Boolean(session.codeVerifier),\n hasTokens: Boolean(session.tokens),\n previousState: this.currentOAuthState,\n state,\n wasInitialized: this.initialized,\n },\n \"adoptState: adopting session (overriding previous state if any)\"\n );\n this.currentOAuthState = state;\n this.cachedAuthData = session;\n this.initialized = true;\n }\n public async invalidateCredentials(\n scope: \"all\" | \"client\" | \"tokens\" | \"verifier\"\n ): Promise<void> {\n if (scope === \"all\" || scope === \"client\") {\n this.cachedAuthorizationUrl = null;\n }\n if (scope === \"all\") {\n await deleteSessionByState({ state: this.currentOAuthState });\n this.cachedAuthData = undefined;\n this.initialized = false;\n this.currentOAuthState = \"\";\n } else if (scope === \"tokens\") {\n await this.updateAuthData({ tokens: null });\n // Clear client credentials - this forces re-registration with the OAuth server\n } else if (scope === \"client\") {\n // Reset state since client info is foundational to the OAuth flow\n await this.updateAuthData({ clientInfo: null });\n this.initialized = false;\n this.currentOAuthState = \"\";\n this.cachedAuthData = undefined;\n // Clear the PKCE verifier - this invalidates any pending authorization\n } else if (scope === \"verifier\") {\n // Clear cached authorization URL since it's tied to the old verifier\n await this.updateAuthData({ codeVerifier: null });\n this.cachedAuthorizationUrl = null;\n }\n }\n}\n",
|
|
163
|
+
"type": "registry:file",
|
|
164
|
+
"target": "~/plugins/mcp/oauth/mcp-oauth-provider.ts"
|
|
165
|
+
},
|
|
166
|
+
{
|
|
167
|
+
"path": "src/plugins/mcp/src/oauth/oauth-authorization-required-error.ts",
|
|
168
|
+
"content": "type ReadonlyNativeSurface<Value> = Value extends\n | string\n | number\n | bigint\n | boolean\n | symbol\n | null\n | undefined\n ? Value\n : Value extends (...parameters: readonly never[]) => unknown\n ? Value\n : Value extends abstract new (...parameters: readonly never[]) => unknown\n ? Value\n : Value extends object\n ? {\n readonly [Property in keyof Value]: ReadonlyNativeSurface<\n Value[Property]\n >;\n }\n : Value;\n\n/**\n * Signals that OAuth authorization must be completed before the MCP client can continue.\n */\nexport class OAuthAuthorizationRequiredError extends Error {\n public authorizationUrl: URL;\n\n public constructor(authorizationUrl: ReadonlyNativeSurface<URL>) {\n super(\"OAuth user authorization required\");\n this.name = \"OAuthAuthorizationRequiredError\";\n this.authorizationUrl = authorizationUrl;\n }\n}\n",
|
|
169
|
+
"type": "registry:file",
|
|
170
|
+
"target": "~/plugins/mcp/oauth/oauth-authorization-required-error.ts"
|
|
171
|
+
},
|
|
172
|
+
{
|
|
173
|
+
"path": "src/plugins/mcp/src/db/mcp-oauth-lock.ts",
|
|
174
|
+
"content": "import type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\nimport postgres from \"postgres\";\n\nimport { databaseConnection } from \"@/lib/db/connection\";\nimport { env } from \"@/lib/env\";\n\nconst OAUTH_LOCK_POOL_IDLE_TIMEOUT_SECONDS = 20;\nconst MAXIMUM_OAUTH_LOCK_CONNECTIONS = 2;\nconst OAUTH_REFRESH_LOCK_TIMEOUT = \"40s\";\nconst connectionConfig = databaseConnection(env);\nconst lockPool = postgres(connectionConfig.url, {\n ...connectionConfig.options,\n idle_timeout: OAUTH_LOCK_POOL_IDLE_TIMEOUT_SECONDS,\n max: Math.min(\n connectionConfig.options.max ?? MAXIMUM_OAUTH_LOCK_CONNECTIONS,\n MAXIMUM_OAUTH_LOCK_CONNECTIONS\n ),\n prepare: false,\n});\n\nconst cancelInactiveQuery = (): void => {\n // No advisory-lock query is waiting to be cancelled.\n};\n\ninterface RefreshCancellation {\n readonly aborted: ReadonlyNativeSurface<Promise<never>>;\n readonly dispose: () => void;\n readonly markStarted: () => void;\n readonly resetQuery: () => void;\n readonly waitFor: <Query extends Readonly<{ cancel: () => void }>>(\n query: Query\n ) => Query;\n}\nconst createRefreshCancellation = (\n signal?: ReadonlyNativeSurface<AbortSignal>\n): RefreshCancellation => {\n const aborted = Promise.withResolvers<never>();\n let refreshStarted = false;\n let cancelQuery = cancelInactiveQuery;\n const cancel = (): void => {\n cancelQuery();\n if (!refreshStarted) {\n aborted.reject(signal?.reason);\n }\n };\n signal?.addEventListener(\"abort\", cancel, { once: true });\n return {\n aborted: aborted.promise,\n dispose: (): void => signal?.removeEventListener(\"abort\", cancel),\n markStarted: (): void => {\n refreshStarted = true;\n },\n resetQuery: (): void => {\n cancelQuery = cancelInactiveQuery;\n },\n waitFor: <Query extends Readonly<{ cancel: () => void }>>(\n query: Query\n ): Query => {\n cancelQuery = (): void => {\n query.cancel();\n };\n return query;\n },\n };\n};\n\ntype LockQuery = (\n template: ReadonlyNativeSurface<TemplateStringsArray>,\n ...parameters: readonly string[]\n) => ReturnType<postgres.TransactionSql>;\nconst createLockedRefresh =\n <Result>(\n options: Readonly<{\n cancellation: RefreshCancellation;\n connectorId: string;\n run: () => Promise<Result>;\n signal?: ReadonlyNativeSurface<AbortSignal>;\n }>\n ): ((transaction: LockQuery) => Promise<{ value: Result }>) =>\n async (transaction: LockQuery): Promise<{ value: Result }> => {\n options.signal?.throwIfAborted();\n await transaction`select set_config('lock_timeout', ${OAUTH_REFRESH_LOCK_TIMEOUT}, true)`;\n options.signal?.throwIfAborted();\n try {\n await options.cancellation.waitFor(\n transaction`select pg_advisory_xact_lock(hashtextextended(${`mcp-oauth-refresh:${options.connectorId}`}, 0))`\n );\n } finally {\n options.cancellation.resetQuery();\n }\n options.signal?.throwIfAborted();\n options.cancellation.markStarted();\n return { value: await options.run() };\n };\n/** Bound refresh lock waiters separately from the app pool used by the refresh callback.\n * @param {string} connectorId - Connector whose refresh is serialized.\n * @param {() => Promise<Result>} run - Refresh operation performed after acquiring the database lock.\n * @param {ReadonlyNativeSurface<AbortSignal> | undefined} signal - Cancellation observed while waiting and before returning the result.\n * @returns {Promise<Result>} The refresh operation result after lock acquisition.\n */\nexport const withMcpOAuthRefreshLock = async <Result>(\n connectorId: string,\n run: () => Promise<Result>,\n signal?: ReadonlyNativeSurface<AbortSignal>\n): Promise<Result> => {\n signal?.throwIfAborted();\n const cancellation = createRefreshCancellation(signal);\n try {\n const operation = lockPool.begin(\n createLockedRefresh({ cancellation, connectorId, run, signal })\n );\n const result = await Promise.race([operation, cancellation.aborted]);\n signal?.throwIfAborted();\n return result.value;\n } finally {\n cancellation.dispose();\n }\n};\n",
|
|
175
|
+
"type": "registry:file",
|
|
176
|
+
"target": "~/plugins/mcp/db/mcp-oauth-lock.ts"
|
|
177
|
+
},
|
|
178
|
+
{
|
|
179
|
+
"path": "src/plugins/mcp/src/db/mcp-queries.ts",
|
|
180
|
+
"content": "export {\n createMcpConnector,\n deleteMcpConnector,\n getMcpConnectorById,\n getMcpConnectorByNameId,\n getMcpConnectorsByUserId,\n updateMcpConnector,\n} from \"./mcp-connector-queries\";\nexport {\n createOAuthSession,\n deletePendingSessionByState,\n deleteSessionByState,\n deleteSessionsByConnectorId,\n getAuthenticatedSession,\n getSessionByState,\n saveTokensAndCleanup,\n setOAuthClientInfoOnceByState,\n setOAuthCodeVerifierOnceByState,\n updateSessionByState,\n} from \"./mcp-oauth-queries\";\nexport type { OAuthClientInformationFull } from \"./mcp-oauth-queries\";\n",
|
|
181
|
+
"type": "registry:file",
|
|
182
|
+
"target": "~/plugins/mcp/db/mcp-queries.ts"
|
|
183
|
+
},
|
|
184
|
+
{
|
|
185
|
+
"path": "src/plugins/mcp/src/db/mcp-connector-queries.ts",
|
|
186
|
+
"content": "import { and, desc, eq, isNull, or, sql } from \"drizzle-orm\";\nimport type { McpConnector } from \"@/plugins/mcp/db/mcp-schema\";\nimport { db } from \"@/lib/db/client\";\nimport { mcpConnector } from \"@/plugins/mcp/db/mcp-schema\";\nimport { createModuleLogger } from \"@/lib/logger\";\n\nconst log = createModuleLogger(\"mcp-queries\");\n// MCP Connector queries\n\nconst getMcpConnectorsByUserId = async ({\n userId,\n}: Readonly<{\n userId: string;\n}>): Promise<McpConnector[]> => {\n try {\n return await db\n .select()\n .from(mcpConnector)\n .where(or(eq(mcpConnector.userId, userId), isNull(mcpConnector.userId)))\n .orderBy(desc(mcpConnector.createdAt));\n } catch (error) {\n log.error({ err: error }, \"Failed to get MCP connectors from database\");\n throw error;\n }\n};\nconst getMcpConnectorById = async ({\n id,\n}: Readonly<{\n id: string;\n}>): Promise<McpConnector | null> => {\n try {\n const [connector] = await db\n .select()\n .from(mcpConnector)\n .where(eq(mcpConnector.id, id));\n return connector ?? null;\n } catch (error) {\n log.error(\n { err: error },\n \"Failed to get MCP connector by id from database\"\n );\n throw error;\n }\n};\nconst getMcpConnectorByNameId = async ({\n userId,\n nameId,\n excludeId,\n}: Readonly<{\n userId: string | null;\n nameId: string;\n excludeId?: string;\n}>): Promise<McpConnector | null> => {\n try {\n const conditions = [\n eq(mcpConnector.nameId, nameId),\n userId === null\n ? isNull(mcpConnector.userId)\n : eq(mcpConnector.userId, userId),\n ];\n\n const whereClause =\n typeof excludeId === \"string\" && excludeId !== \"\"\n ? and(...conditions, sql`${mcpConnector.id} != ${excludeId}::uuid`)\n : and(...conditions);\n\n const [connector] = await db.select().from(mcpConnector).where(whereClause);\n return connector ?? null;\n } catch (error) {\n log.error(\n { err: error },\n \"Failed to get MCP connector by nameId from database\"\n );\n throw error;\n }\n};\nconst createMcpConnector = async ({\n userId,\n name,\n nameId,\n url,\n type,\n oauthClientId,\n oauthClientSecret,\n}: Readonly<{\n userId: string | null;\n name: string;\n nameId: string;\n url: string;\n type: \"http\" | \"sse\";\n oauthClientId?: string;\n oauthClientSecret?: string;\n}>): Promise<McpConnector> => {\n try {\n const [connector] = await db\n .insert(mcpConnector)\n .values({\n name,\n nameId,\n oauthClientId: oauthClientId ?? null,\n oauthClientSecret: oauthClientSecret ?? null,\n type,\n url,\n userId,\n })\n .returning();\n return connector;\n } catch (error) {\n log.error({ err: error }, \"Failed to create MCP connector in database\");\n throw error;\n }\n};\nconst updateMcpConnector = async ({\n id,\n updates,\n}: Readonly<{\n id: string;\n updates: Readonly<\n Partial<{\n name: string;\n nameId: string;\n url: string;\n type: \"http\" | \"sse\";\n oauthClientId: string | null;\n oauthClientSecret: string | null;\n enabled: boolean;\n requireApproval: boolean;\n }>\n >;\n}>): Promise<void> => {\n try {\n await db\n .update(mcpConnector)\n .set({\n ...updates,\n updatedAt: new Date(),\n })\n .where(eq(mcpConnector.id, id));\n } catch (error) {\n log.error({ err: error }, \"Failed to update MCP connector in database\");\n throw error;\n }\n};\nconst deleteMcpConnector = async ({\n id,\n}: Readonly<{ id: string }>): Promise<void> => {\n try {\n await db.delete(mcpConnector).where(eq(mcpConnector.id, id));\n } catch (error) {\n log.error({ err: error }, \"Failed to delete MCP connector from database\");\n throw error;\n }\n};\nexport {\n createMcpConnector,\n deleteMcpConnector,\n getMcpConnectorById,\n getMcpConnectorByNameId,\n getMcpConnectorsByUserId,\n updateMcpConnector,\n};\n",
|
|
187
|
+
"type": "registry:file",
|
|
188
|
+
"target": "~/plugins/mcp/db/mcp-connector-queries.ts"
|
|
189
|
+
},
|
|
190
|
+
{
|
|
191
|
+
"path": "src/plugins/mcp/src/db/mcp-oauth-queries.ts",
|
|
192
|
+
"content": "import type {\n OAuthClientInformation,\n OAuthClientMetadata,\n OAuthTokens,\n} from \"@ai-sdk/mcp\";\nimport { and, desc, eq, isNotNull, isNull, ne, sql } from \"drizzle-orm\";\nimport type { McpOAuthSession } from \"@/plugins/mcp/db/mcp-schema\";\nimport { db } from \"@/lib/db/client\";\nimport { mcpOAuthSession } from \"@/plugins/mcp/db/mcp-schema\";\nimport { createModuleLogger } from \"@/lib/logger\";\n\nconst AUTHENTICATED_SESSION_LIMIT = 1;\nconst EMPTY_UPDATE_COUNT = 0;\nconst FIRST_QUERY_ROW_INDEX = 0;\nconst OMITTED_COLUMN_UPDATE = undefined;\n\nconst log = createModuleLogger(\"mcp-queries\");\n\n// Full client information includes both metadata and registration response\ntype OAuthClientInformationFull = OAuthClientMetadata & OAuthClientInformation;\ntype ReadonlyMetadataValue<Value> = Value extends readonly unknown[]\n ? Readonly<Value>\n : Value;\ntype ReadonlyClientInformation = {\n readonly [\n Property in keyof Omit<OAuthClientInformationFull, \"jwks\">\n ]: ReadonlyMetadataValue<OAuthClientInformationFull[Property]>;\n} & { readonly jwks?: unknown };\n\n// MCP OAuth Session queries\n\nconst getAuthenticatedSession = async ({\n mcpConnectorId,\n}: Readonly<{\n mcpConnectorId: string;\n}>): Promise<McpOAuthSession | undefined> => {\n const [session] = await db\n .select()\n .from(mcpOAuthSession)\n .where(\n and(\n eq(mcpOAuthSession.mcpConnectorId, mcpConnectorId),\n isNotNull(mcpOAuthSession.tokens)\n )\n )\n .orderBy(desc(mcpOAuthSession.updatedAt))\n .limit(AUTHENTICATED_SESSION_LIMIT);\n return session;\n};\nconst getSessionByState = async ({\n state,\n}: Readonly<{ state: string }>): Promise<McpOAuthSession | undefined> => {\n const rows =\n state === \"\"\n ? []\n : await db\n .select()\n .from(mcpOAuthSession)\n .where(eq(mcpOAuthSession.state, state));\n return rows.at(FIRST_QUERY_ROW_INDEX);\n};\nconst createOAuthSession = async ({\n mcpConnectorId,\n serverUrl,\n state,\n codeVerifier,\n clientInfo,\n}: Readonly<{\n mcpConnectorId: string;\n serverUrl: string;\n state: string;\n codeVerifier?: string;\n clientInfo?: ReadonlyClientInformation;\n}>): Promise<McpOAuthSession> => {\n // Preserve active authorization attempts while pruning abandoned expired attempts.\n try {\n await db\n .delete(mcpOAuthSession)\n .where(\n and(\n eq(mcpOAuthSession.mcpConnectorId, mcpConnectorId),\n isNull(mcpOAuthSession.tokens),\n sql`${mcpOAuthSession.createdAt} < now() - interval '1 hour'`\n )\n );\n } catch (error) {\n log.warn(\n { err: error, mcpConnectorId },\n \"Could not clean up expired OAuth sessions\"\n );\n }\n const [session] = await db\n .insert(mcpOAuthSession)\n .values({\n clientInfo,\n codeVerifier,\n mcpConnectorId,\n serverUrl,\n state,\n })\n .returning();\n return session;\n};\nconst requireSessionByState = async (\n state: string\n): Promise<McpOAuthSession> => {\n const rows = await db\n .select()\n .from(mcpOAuthSession)\n .where(eq(mcpOAuthSession.state, state));\n const session = rows.at(FIRST_QUERY_ROW_INDEX);\n if (!session) {\n throw new Error(`Session with state ${state} not found`);\n }\n return session;\n};\nconst setOAuthCodeVerifierOnceByState = async ({\n state,\n codeVerifier,\n}: Readonly<{\n state: string;\n codeVerifier: string;\n}>): Promise<McpOAuthSession> => {\n const updatedRows = await db\n .update(mcpOAuthSession)\n .set({ codeVerifier })\n .where(\n and(\n eq(mcpOAuthSession.state, state),\n isNull(mcpOAuthSession.codeVerifier)\n )\n )\n .returning();\n const updated = updatedRows.at(FIRST_QUERY_ROW_INDEX);\n\n if (updated) {\n return updated;\n }\n\n return await requireSessionByState(state);\n};\nconst setOAuthClientInfoOnceByState = async ({\n state,\n clientInfo,\n}: Readonly<{\n state: string;\n clientInfo: ReadonlyClientInformation;\n}>): Promise<McpOAuthSession> => {\n const updatedRows = await db\n .update(mcpOAuthSession)\n .set({ clientInfo })\n .where(\n and(eq(mcpOAuthSession.state, state), isNull(mcpOAuthSession.clientInfo))\n )\n .returning();\n const updated = updatedRows.at(FIRST_QUERY_ROW_INDEX);\n\n if (updated) {\n return updated;\n }\n\n return await requireSessionByState(state);\n};\nconst updateSessionByState = async ({\n state,\n updates,\n}: Readonly<{\n state: string;\n updates: Readonly<{\n tokens?: Readonly<OAuthTokens> | null;\n clientInfo?: ReadonlyClientInformation | null;\n codeVerifier?: string | null;\n }>;\n}>): Promise<McpOAuthSession> => {\n // Filter out undefined values - only include explicit values (including null)\n const setValues = Object.fromEntries(\n Object.entries(updates).filter(\n ([, value]: readonly [unknown, unknown]): boolean =>\n value !== OMITTED_COLUMN_UPDATE\n )\n );\n\n if (Object.keys(setValues).length === EMPTY_UPDATE_COUNT) {\n return await requireSessionByState(state);\n }\n\n const sessionRows = await db\n .update(mcpOAuthSession)\n .set(setValues)\n .where(eq(mcpOAuthSession.state, state))\n .returning();\n const session = sessionRows.at(FIRST_QUERY_ROW_INDEX);\n if (!session) {\n throw new Error(`Session with state ${state} not found`);\n }\n return session;\n};\nconst saveTokensAndCleanup = async ({\n state,\n mcpConnectorId,\n tokens,\n}: Readonly<{\n state: string;\n mcpConnectorId: string;\n tokens: Readonly<OAuthTokens>;\n}>): Promise<McpOAuthSession> => {\n const sessionRows = await db\n .update(mcpOAuthSession)\n .set({ tokens })\n .where(eq(mcpOAuthSession.state, state))\n .returning();\n const session = sessionRows.at(FIRST_QUERY_ROW_INDEX);\n\n if (!session) {\n throw new Error(`Session with state ${state} not found`);\n }\n\n try {\n await db\n .delete(mcpOAuthSession)\n .where(\n and(\n eq(mcpOAuthSession.mcpConnectorId, mcpConnectorId),\n isNull(mcpOAuthSession.tokens),\n sql`${mcpOAuthSession.createdAt} < now() - interval '1 hour'`,\n ne(mcpOAuthSession.state, state)\n )\n );\n } catch (error) {\n log.warn(\n { err: error, mcpConnectorId },\n \"Could not clean up expired OAuth sessions\"\n );\n }\n\n return session;\n};\n/** Remove only an unfinished OAuth attempt, atomically preserving any token winner.\n * @param {Readonly<{ state: string }>} options - State identifying the unfinished authorization attempt.\n * @returns {Promise<McpOAuthSession | null>} The removed row when no token winner was present.\n */\nconst deletePendingSessionByState = async (\n options: Readonly<{ state: string }>\n): Promise<McpOAuthSession | null> => {\n const { state } = options;\n const [session] = await db\n .delete(mcpOAuthSession)\n .where(\n and(eq(mcpOAuthSession.state, state), isNull(mcpOAuthSession.tokens))\n )\n .returning();\n return session ?? null;\n};\nconst deleteSessionByState = async ({\n state,\n}: Readonly<{\n state: string;\n}>): Promise<void> => {\n await db.delete(mcpOAuthSession).where(eq(mcpOAuthSession.state, state));\n};\nconst deleteSessionsByConnectorId = async ({\n mcpConnectorId,\n}: Readonly<{\n mcpConnectorId: string;\n}>): Promise<void> => {\n await db\n .delete(mcpOAuthSession)\n .where(eq(mcpOAuthSession.mcpConnectorId, mcpConnectorId));\n};\nexport {\n createOAuthSession,\n deletePendingSessionByState,\n deleteSessionByState,\n deleteSessionsByConnectorId,\n getAuthenticatedSession,\n getSessionByState,\n saveTokensAndCleanup,\n setOAuthClientInfoOnceByState,\n setOAuthCodeVerifierOnceByState,\n updateSessionByState,\n};\nexport type { OAuthClientInformationFull };\n",
|
|
193
|
+
"type": "registry:file",
|
|
194
|
+
"target": "~/plugins/mcp/db/mcp-oauth-queries.ts"
|
|
195
|
+
},
|
|
196
|
+
{
|
|
197
|
+
"path": "src/plugins/mcp/src/runtime/mcp-tools.ts",
|
|
198
|
+
"content": "import type { ModelMessage, Tool } from \"ai\";\nimport { createHash } from \"node:crypto\";\nimport { asSchema, jsonSchema } from \"ai\";\nimport { describeMcpTool, executeMcpTool } from \"./mcp-adapter\";\nimport Ajv from \"ajv\";\nimport Ajv2020 from \"ajv/dist/2020.js\";\nimport type { McpConnector } from \"@/plugins/mcp/db/mcp-schema\";\nimport type { ToolContext } from \"eve/tools\";\nimport { requireMcpCredentials } from \"@/plugins/mcp/setup\";\nimport { MCPClient } from \"@/plugins/mcp/oauth/mcp-client\";\nimport { createModuleLogger } from \"@/lib/logger\";\nimport { createToolId } from \"@/lib/ai/mcp-name-id\";\nimport { installedPlugins } from \"@/composition/generated/installed\";\nimport {\n getMcpConnectorById,\n getMcpConnectorsByUserId,\n} from \"@/plugins/mcp/db/mcp-queries\";\nimport { eveMcpResult } from \"@/lib/eve/mcp-result\";\n\n// Read-only native session/approval metadata and cancellation used by MCP adapters.\ntype McpToolContext = Readonly<{\n session: ToolContext[\"session\"];\n callId: ToolContext[\"callId\"];\n abortSignal: Readonly<AbortSignal>;\n approval?: Readonly<Pick<NonNullable<ToolContext[\"approval\"]>, \"responder\">>;\n}>;\n\nconst log = createModuleLogger(\"eve.mcp\");\n\nconst FIRST_CHARACTER_INDEX = 0;\nconst TOOL_NAME_PREFIX_LENGTH = 51;\nconst TOOL_NAME_HASH_LENGTH = 12;\nconst CONNECTOR_DISCOVERY_TIMEOUT_MS = 10_000;\nconst CONNECTOR_DISCOVERY_CONCURRENCY = 2;\nconst MCP_APPROVAL_TIMEOUT_MS = 30_000;\nconst MAXIMUM_VALIDATION_ERRORS = 3;\ntype ValidatedMcpTool<NativeTool> = NativeTool extends Tool\n ? Omit<NativeTool, \"inputSchema\"> & {\n inputSchema: ReturnType<typeof jsonSchema<Record<string, unknown>>>;\n }\n : never;\n\nconst VALID_TOOL_NAME = /^[a-zA-Z0-9_-]{1,64}$/u;\nconst UNSAFE_TOOL_NAME = /[^a-zA-Z0-9_-]/gu;\n\nconst modelToolName = (name: string): string => {\n if (VALID_TOOL_NAME.test(name)) {\n return name;\n }\n return `${name.replace(UNSAFE_TOOL_NAME, \"_\").slice(FIRST_CHARACTER_INDEX, TOOL_NAME_PREFIX_LENGTH)}_${createHash(\"sha256\").update(name).digest(\"hex\").slice(FIRST_CHARACTER_INDEX, TOOL_NAME_HASH_LENGTH)}`;\n};\n\nconst withAbort = async <T>(\n operation: () => Promise<T>,\n signal: Readonly<\n Pick<\n AbortSignal,\n | \"throwIfAborted\"\n | \"reason\"\n | \"addEventListener\"\n | \"removeEventListener\"\n | \"aborted\"\n >\n >\n): Promise<T> => {\n signal.throwIfAborted();\n const aborted = Promise.withResolvers<never>();\n const cancel = (): void => {\n aborted.reject(signal.reason);\n };\n signal.addEventListener(\"abort\", cancel, { once: true });\n try {\n return await Promise.race([operation(), aborted.promise]);\n } finally {\n signal.removeEventListener(\"abort\", cancel);\n }\n};\n\nconst assertConnector = (\n connector: Readonly<\n Pick<\n McpConnector,\n | \"enabled\"\n | \"userId\"\n | \"id\"\n | \"name\"\n | \"oauthClientId\"\n | \"oauthClientSecret\"\n | \"type\"\n | \"url\"\n | \"requireApproval\"\n >\n > | null,\n ownerId: string\n): Readonly<\n Pick<\n McpConnector,\n | \"enabled\"\n | \"userId\"\n | \"id\"\n | \"name\"\n | \"oauthClientId\"\n | \"oauthClientSecret\"\n | \"type\"\n | \"url\"\n | \"requireApproval\"\n >\n> => {\n if (\n !(\n installedPlugins.has(\"mcp\") &&\n connector?.enabled === true &&\n (connector.userId === ownerId || connector.userId === null)\n )\n ) {\n throw new Error(\"MCP connector is unavailable.\");\n }\n requireMcpCredentials();\n return connector;\n};\n\nconst withConnector = async <T>(\n connector: Readonly<\n Pick<\n McpConnector,\n \"id\" | \"name\" | \"oauthClientId\" | \"oauthClientSecret\" | \"type\" | \"url\"\n >\n >,\n signal: Readonly<\n Pick<\n AbortSignal,\n | \"throwIfAborted\"\n | \"reason\"\n | \"addEventListener\"\n | \"removeEventListener\"\n | \"aborted\"\n >\n >,\n run: (tools: Record<string, Tool>) => Promise<T>\n): Promise<T> => {\n signal.throwIfAborted();\n const client = new MCPClient(connector.id, connector.name, {\n oauthClientId: connector.oauthClientId,\n oauthClientSecret: connector.oauthClientSecret,\n type: connector.type,\n url: connector.url,\n });\n let closing: Promise<void> | undefined;\n const close = async (): Promise<void> => {\n closing ??= client.close();\n await closing;\n };\n const closeAfterAbort = async (): Promise<void> => {\n try {\n await close();\n } catch {\n // The scope's finally awaits the same close and reports its failure.\n }\n };\n const cancel = (): void => {\n void closeAfterAbort();\n };\n signal.addEventListener(\"abort\", cancel, { once: true });\n try {\n await withAbort(async () => {\n await client.connect({ abortSignal: signal });\n }, signal);\n signal.throwIfAborted();\n if (client.status !== \"connected\") {\n throw new Error(\n \"Connect this MCP server in settings before using its tools.\"\n );\n }\n const tools = await withAbort(async () => await client.tools(), signal);\n signal.throwIfAborted();\n return await withAbort(async () => await run(tools), signal);\n } finally {\n signal.removeEventListener(\"abort\", cancel);\n await close();\n }\n};\n/**\n * Discovers serializable MCP descriptions while closing every opened connector client.\n * @param {string | undefined} ownerId Authenticated owner whose enabled connectors may be discovered; absence yields no tools.\n * @param {AbortSignal} signal Discovery cancellation boundary combined with each connector's connection timeout.\n * @returns {Promise< (Awaited<ReturnType<typeof describeMcpTool>> & { name: string; connectorId: string; remoteName: string; })[] >} Safe model tool names and serializable remote descriptions/identities for durable use.\n */\nconst discoverEveMcpTools = async (\n ownerId: string | undefined,\n signal: Readonly<AbortSignal>\n): Promise<\n (Awaited<ReturnType<typeof describeMcpTool>> & {\n name: string;\n connectorId: string;\n remoteName: string;\n })[]\n> => {\n if (\n !(\n typeof ownerId === \"string\" &&\n ownerId !== \"\" &&\n installedPlugins.has(\"mcp\")\n )\n ) {\n return [];\n }\n requireMcpCredentials();\n const connectors = await withAbort(\n async () => await getMcpConnectorsByUserId({ userId: ownerId }),\n signal\n );\n const descriptions: (Awaited<ReturnType<typeof describeMcpTool>> & {\n name: string;\n connectorId: string;\n remoteName: string;\n })[] = [];\n const enabledConnectors = connectors.filter((connector) => connector.enabled);\n for (\n let offset = 0;\n offset < enabledConnectors.length;\n offset += CONNECTOR_DISCOVERY_CONCURRENCY\n ) {\n if (\n signal.aborted &&\n signal.reason instanceof DOMException &&\n signal.reason.name === \"TimeoutError\"\n ) {\n break;\n }\n signal.throwIfAborted();\n // oxlint-disable-next-line eslint/no-await-in-loop -- Keep at most two live connector scopes and await every close before admitting another batch or returning cancellation.\n const batch = await Promise.allSettled(\n enabledConnectors\n .slice(offset, offset + CONNECTOR_DISCOVERY_CONCURRENCY)\n .map(async (connector) => {\n const connectorDescriptions: typeof descriptions = [];\n const connectorSignal = AbortSignal.any([\n signal,\n AbortSignal.timeout(CONNECTOR_DISCOVERY_TIMEOUT_MS),\n ]);\n try {\n await withConnector(\n assertConnector(connector, ownerId),\n connectorSignal,\n async (tools): Promise<void> => {\n for (const [remoteName, tool] of Object.entries(tools)) {\n connectorSignal.throwIfAborted();\n try {\n // MCP output and approval policies are adapted explicitly below.\n const { toModelOutput: _outputAdapter, ...definition } =\n tool;\n // oxlint-disable-next-line no-await-in-loop -- Resolve one tool schema at a time and check cancellation before starting the next conversion within this connector's discovery window.\n const description = await describeMcpTool(definition);\n connectorSignal.throwIfAborted();\n connectorDescriptions.push({\n ...description,\n connectorId: connector.id,\n name: modelToolName(\n createToolId(\n connector.nameId,\n remoteName,\n connector.userId === null\n )\n ),\n remoteName,\n });\n } catch {\n connectorSignal.throwIfAborted();\n log.warn(\n { connectorId: connector.id, remoteName },\n \"Unsupported MCP tool schema\"\n );\n }\n }\n }\n );\n } catch {\n if (\n signal.aborted &&\n signal.reason instanceof DOMException &&\n signal.reason.name === \"TimeoutError\"\n ) {\n return connectorDescriptions;\n }\n signal.throwIfAborted();\n log.warn(\n { connectorId: connector.id },\n \"MCP discovery unavailable\"\n );\n }\n return connectorDescriptions;\n })\n );\n for (const result of batch) {\n if (result.status === \"rejected\") {\n throw result.reason;\n }\n descriptions.push(...result.value);\n }\n }\n return descriptions;\n};\n\nconst validateMcpTool = async (tool: Tool): Promise<ValidatedMcpTool<Tool>> => {\n const schema = await asSchema(tool.inputSchema).jsonSchema;\n // MCP defaults to 2020-12; retain explicitly declared draft-07 schemas.\n const Validator =\n schema.$schema === \"http://json-schema.org/draft-07/schema#\"\n ? Ajv\n : Ajv2020;\n const validate = new Validator({\n strict: false,\n validateFormats: false,\n }).compile(schema);\n return {\n ...tool,\n inputSchema: jsonSchema(schema, {\n validate: (value) => {\n if (validate(value)) {\n return { success: true, value };\n }\n return {\n error: new Error(\n `Invalid tool input: ${\n validate.errors\n ?.slice(FIRST_CHARACTER_INDEX, MAXIMUM_VALIDATION_ERRORS)\n .map(\n (error: {\n readonly instancePath: string;\n readonly message?: string | undefined;\n }): string => `${error.instancePath || \"/\"} ${error.message}`\n )\n .join(\"; \") ?? \"schema validation failed\"\n }`\n ),\n success: false,\n };\n },\n }),\n };\n};\n\nconst validateMcpInput = async (\n tool: Readonly<Pick<Tool, \"inputSchema\">>,\n input: unknown\n): Promise<void> => {\n const validated = await asSchema(tool.inputSchema).validate?.(input);\n if (validated?.success !== true) {\n if (validated?.success === false) {\n throw validated.error;\n }\n throw new Error(\"Invalid tool input.\");\n }\n};\n\nconst executeEveMcpTool = async (\n connectorId: string,\n remoteName: string,\n input: unknown,\n context: McpToolContext,\n messages: readonly ModelMessage[]\n): Promise<ReturnType<typeof eveMcpResult.parse>> => {\n const ownerId = context.session.auth.initiator?.principalId;\n if (!(typeof ownerId === \"string\" && ownerId !== \"\")) {\n throw new Error(\"MCP tools require an authenticated owner.\");\n }\n context.abortSignal.throwIfAborted();\n const connector = assertConnector(\n await withAbort(\n async () => await getMcpConnectorById({ id: connectorId }),\n context.abortSignal\n ),\n ownerId\n );\n return await withConnector(connector, context.abortSignal, async (tools) => {\n if (!Object.hasOwn(tools, remoteName)) {\n throw new Error(\"MCP tool is no longer available.\");\n }\n const tool = tools[remoteName];\n const validatedTool = await validateMcpTool(tool);\n // EVE binds this receipt to the exact session, tool, call and input.\n // Use the current persisted connector policy, not discovered SDK metadata.\n if (\n connector.requireApproval &&\n context.approval?.responder.principalId !== ownerId\n ) {\n throw new Error(\"MCP tools require an owner approval receipt.\");\n }\n let result: unknown;\n for await (const output of executeMcpTool(\n validatedTool,\n input,\n context,\n messages\n )) {\n result = output;\n }\n const converted = tool.toModelOutput\n ? await tool.toModelOutput({\n input,\n output: result,\n toolCallId: context.callId,\n })\n : { type: \"json\", value: result };\n return eveMcpResult.parse({\n kind: \"chatjs.mcp-result\",\n modelOutput: converted,\n output: result,\n });\n });\n};\n/**\n * Evaluates current MCP approval policy using serializable identifiers and a temporary client.\n * @param {string} connectorId Connector identity resolved against the authenticated owner and installed MCP plugin.\n * @param {string} remoteName Exact remote tool name whose availability and schema are rechecked.\n * @param {unknown} input Tool input validated before its current approval policy is evaluated.\n * @param {Pick<McpToolContext, \"session\" | \"abortSignal\">} context Native session authentication and cancellation evidence.\n * @returns {Promise<\"user-approval\" | \"not-applicable\">} Whether the current tool requires user approval; the temporary client closes on all paths.\n */\nconst requestEveMcpApproval = async (\n connectorId: string,\n remoteName: string,\n input: unknown,\n context: Pick<McpToolContext, \"session\" | \"abortSignal\">\n): Promise<\"user-approval\" | \"not-applicable\"> => {\n const ownerId = context.session.auth.initiator?.principalId;\n if (!(typeof ownerId === \"string\" && ownerId !== \"\")) {\n throw new Error(\"MCP tools require an authenticated owner.\");\n }\n const signal = AbortSignal.any([\n context.abortSignal,\n AbortSignal.timeout(MCP_APPROVAL_TIMEOUT_MS),\n ]);\n const connector = assertConnector(\n await withAbort(\n async () => await getMcpConnectorById({ id: connectorId }),\n signal\n ),\n ownerId\n );\n return await withConnector(connector, signal, async (tools) => {\n if (!Object.hasOwn(tools, remoteName)) {\n throw new Error(\"MCP tool is no longer available.\");\n }\n await validateMcpInput(await validateMcpTool(tools[remoteName]), input);\n\n if (connector.requireApproval) {\n return \"user-approval\";\n }\n return \"not-applicable\";\n });\n};\n\nexport {\n discoverEveMcpTools,\n executeEveMcpTool,\n requestEveMcpApproval,\n type McpToolContext,\n};\n",
|
|
199
|
+
"type": "registry:file",
|
|
200
|
+
"target": "~/plugins/mcp/runtime/mcp-tools.ts"
|
|
201
|
+
},
|
|
202
|
+
{
|
|
203
|
+
"path": "src/plugins/mcp/src/runtime/mcp-adapter.ts",
|
|
204
|
+
"content": "import type { ModelMessage, Tool } from \"ai\";\nimport type { ToolContext } from \"eve/tools\";\nimport { asSchema } from \"ai\";\nimport { z } from \"zod\";\n\nconst isAsyncIterable = <Output>(\n value: unknown\n): value is AsyncIterable<Output> =>\n typeof value === \"object\" &&\n value !== null &&\n Symbol.asyncIterator in value &&\n typeof value[Symbol.asyncIterator] === \"function\";\n\n/** Describe discovered MCP tools; approval and output policies are handled by the MCP integration.\n * @param {Readonly<Pick<Tool<TInput, TOutput>, \"description\" | \"inputSchema\" | \"type\"> & { toModelOutput?: unknown }>} definition - Native input schema and description metadata; output policies are detected and rejected without invoking or inspecting their signatures.\n * @returns {Promise<{ description: string; inputSchema: Record<string, z.infer<ReturnType<typeof z.json>>>; }>} A serializable description and validated JSON input schema.\n */\nconst describeMcpTool = async <TInput, TOutput>(\n definition: Readonly<\n Pick<Tool<TInput, TOutput>, \"description\" | \"inputSchema\" | \"type\"> & {\n toModelOutput?: unknown;\n }\n >\n): Promise<{\n description: string;\n inputSchema: Record<string, z.infer<ReturnType<typeof z.json>>>;\n}> => {\n if (\n typeof definition.toModelOutput === \"function\" ||\n definition.type === \"provider\" ||\n typeof definition.description === \"function\"\n ) {\n throw new Error(\"This tool requires an explicit Eve policy adapter.\");\n }\n const schema = asSchema(definition.inputSchema);\n const inputSchema = z\n .record(z.string(), z.json())\n // The AI SDK attaches executable Standard Schema metadata to JSON schemas.\n .parse(\n JSON.parse(\n JSON.stringify(\n await schema.jsonSchema,\n (key: string, value: unknown): unknown => {\n if (key === \"~standard\") {\n return undefined;\n }\n return value;\n }\n )\n )\n );\n return {\n description: definition.description ?? \"Application tool\",\n inputSchema,\n };\n};\n/**\n * Resolve module-level definitions at execution time, avoiding executable captures in durable closures.\n * @param {Readonly<Pick<Tool<TInput, TOutput>, \"inputSchema\" | \"execute\">>} definition - Native schema and executor resolved at call time.\n * @param {unknown} input - Untrusted input validated by the SDK schema.\n * @param {Readonly<{ callId: ToolContext[\"callId\"]; abortSignal: Readonly<AbortSignal>; }>} context - Call identity and cancellation.\n * @param {readonly ModelMessage[]} messages - Prior model messages.\n * @yields {unknown} Each output emitted by the installed AI SDK tool.\n */\nconst executeMcpTool = async function* executeMcpTool<TInput, TOutput>(\n definition: Readonly<Pick<Tool<TInput, TOutput>, \"inputSchema\" | \"execute\">>,\n input: unknown,\n context: Readonly<{\n callId: ToolContext[\"callId\"];\n abortSignal: Readonly<AbortSignal>;\n }>,\n messages: readonly ModelMessage[]\n): AsyncGenerator<Awaited<TOutput>, void, unknown> {\n const schema = asSchema(definition.inputSchema);\n if (!(schema.validate && definition.execute)) {\n throw new Error(\"Tool validation and execution are required.\");\n }\n const result = await schema.validate(input);\n if (!result.success) {\n throw new Error(\"Invalid tool input.\");\n }\n const output = await definition.execute(result.value, {\n abortSignal: context.abortSignal,\n context: undefined,\n messages: [...messages],\n toolCallId: context.callId,\n });\n if (isAsyncIterable<TOutput>(output)) {\n yield* output;\n } else {\n yield output;\n }\n};\nexport { describeMcpTool, executeMcpTool };\n",
|
|
205
|
+
"type": "registry:file",
|
|
206
|
+
"target": "~/plugins/mcp/runtime/mcp-adapter.ts"
|
|
207
|
+
},
|
|
208
|
+
{
|
|
209
|
+
"path": "src/plugins/mcp/src/search/mcp-search-params.ts",
|
|
210
|
+
"content": "import { parseAsString, parseAsStringEnum } from \"nuqs\";\n\nconst mcpConnectorsDialogValues = [\"config\", \"connect\"] as const;\n\nexport type McpConnectorsDialog = (typeof mcpConnectorsDialogValues)[number];\n\n/**\n * Query params for the /settings/connectors page.\n *\n * - dialog=config: open create/edit dialog (connectorId optional)\n * - dialog=connect: open connect dialog (connectorId required)\n */\nexport const mcpConnectorsSettingsSearchParams = {\n connectorId: parseAsString,\n dialog: parseAsStringEnum([...mcpConnectorsDialogValues]),\n};\n",
|
|
211
|
+
"type": "registry:file",
|
|
212
|
+
"target": "~/plugins/mcp/search/mcp-search-params.ts"
|
|
213
|
+
},
|
|
214
|
+
{
|
|
215
|
+
"path": "src/plugins/mcp/src/search/mcp-search-params.server.ts",
|
|
216
|
+
"content": "import { createLoader, parseAsString } from \"nuqs/server\";\n\n/**\n * IMPORTANT:\n * This file must only use parsers imported from `nuqs/server`.\n * Importing parsers from `nuqs` here can produce parser objects without\n * `serialize()` at runtime (route handlers), which breaks serializer/loader helpers.\n */\n\nconst mcpOAuthCallbackSearchParamsServer = {\n code: parseAsString,\n error: parseAsString,\n error_description: parseAsString,\n state: parseAsString,\n};\n\nexport const loadMcpOAuthCallbackSearchParams = createLoader(\n mcpOAuthCallbackSearchParamsServer\n);\n",
|
|
217
|
+
"type": "registry:file",
|
|
218
|
+
"target": "~/plugins/mcp/search/mcp-search-params.server.ts"
|
|
219
|
+
},
|
|
220
|
+
{
|
|
221
|
+
"path": "src/plugins/mcp/src/router.ts",
|
|
222
|
+
"content": "import type {\n ConnectionStatusResult,\n DiscoveryResult,\n} from \"@/plugins/mcp/oauth/cache\";\nimport { MCP_NAME_MAX_LENGTH, generateMcpNameId } from \"@/lib/ai/mcp-name-id\";\nimport { MissingCredentialsError } from \"@/lib/required-credentials\";\nimport { TRPCError } from \"@trpc/server\";\nimport { assertUrlIsSafeToFetch } from \"guarded-fetch\";\nimport { z } from \"zod\";\nimport { requireMcpCredentials } from \"@/plugins/mcp/setup\";\nimport {\n createCachedConnectionStatus,\n createCachedDiscovery,\n invalidateAllMcpCaches,\n} from \"@/plugins/mcp/oauth/cache\";\nimport {\n getOrCreateMcpClient,\n removeMcpClient,\n} from \"@/plugins/mcp/oauth/mcp-client-manager\";\nimport { createModuleLogger } from \"@/lib/logger\";\nimport { installedPlugins } from \"@/composition/generated/installed\";\nimport {\n createMcpConnector,\n deleteMcpConnector,\n deleteSessionsByConnectorId,\n getAuthenticatedSession,\n getMcpConnectorById,\n getMcpConnectorByNameId,\n getMcpConnectorsByUserId,\n updateMcpConnector,\n} from \"@/plugins/mcp/db/mcp-queries\";\nimport { createTRPCRouter, protectedProcedure } from \"@/trpc/init\";\n\n// Procedure callbacks read only the authenticated user identity from tRPC context.\ntype McpProcedureContext = Readonly<{ user: Readonly<{ id: string }> }>;\n\ntype McpConnectorReader = Readonly<\n PublicConnectorInput &\n Pick<McpConnectorRow, \"oauthClientId\" | \"oauthClientSecret\">\n>;\ntype McpConnectionResultReader = Readonly<{\n connector: McpConnectorReader;\n status: Readonly<ConnectionStatusResult> | null;\n}>;\n\ntype McpResourceReader = Readonly<{\n description?: string;\n mimeType?: string;\n name: string;\n uri: string;\n}>;\ntype McpPromptArgumentReader = Readonly<{\n description?: string;\n name: string;\n required?: boolean;\n}>;\ntype McpPromptReader = Readonly<{\n arguments?: readonly McpPromptArgumentReader[];\n description?: string;\n name: string;\n}>;\n\nconst log = createModuleLogger(\"mcp.router\");\n\nconst assertMcpReady = (): void => {\n if (!installedPlugins.has(\"mcp\")) {\n throw new TRPCError({\n code: \"PRECONDITION_FAILED\",\n message: \"MCP is not installed\",\n });\n }\n try {\n requireMcpCredentials();\n } catch (error) {\n if (error instanceof MissingCredentialsError) {\n throw new TRPCError({\n cause: error,\n code: \"PRECONDITION_FAILED\",\n message: error.message,\n });\n }\n throw error;\n }\n};\n\n/**\n * Validates and generates a nameId from a connector name.\n * Throws TRPCError if the name is invalid or the namespace already exists.\n * @param {Readonly<{ name: string; userId: string | null; excludeId?: string; }>} options - Candidate name, namespace owner, and connector excluded during rename.\n * @returns {Promise<string>} The validated available connector namespace.\n */\nconst validateAndGenerateNameId = async ({\n name,\n userId,\n excludeId,\n}: {\n readonly name: string;\n readonly userId: string | null;\n readonly excludeId?: string;\n}): Promise<string> => {\n assertMcpReady();\n const result = generateMcpNameId(name);\n if (!result.ok) {\n throw new TRPCError({\n code: \"BAD_REQUEST\",\n message:\n result.error === \"empty\"\n ? \"Connector name must contain at least one alphanumeric character\"\n : 'Connector name cannot be \"global\" (reserved)',\n });\n }\n\n const existing = await getMcpConnectorByNameId({\n excludeId,\n nameId: result.nameId,\n userId,\n });\n\n if (existing) {\n throw new TRPCError({\n code: \"CONFLICT\",\n message: `A connector with namespace \"${result.nameId}\" already exists. Choose a different name.`,\n });\n }\n\n return result.nameId;\n};\n\ntype Permission = \"own\" | \"own-or-global\";\n\n/**\n * Fetches connector and validates user permission.\n * - \"own\": user must own the connector (userId === ctx.user.id)\n * - \"own-or-global\": user must own OR connector is global (userId === null)\n * @param {Readonly<{ id: string; userId: string; permission: Permission; }>} options - Connector identity and required ownership permission.\n * @returns {Promise<McpConnectorRow>} The connector after permission validation.\n */\nconst getConnectorWithPermission = async ({\n id,\n userId,\n permission,\n}: {\n readonly id: string;\n readonly userId: string;\n readonly permission: Permission;\n}): Promise<McpConnectorRow> => {\n const connector = await getMcpConnectorById({ id });\n if (!connector) {\n throw new TRPCError({ code: \"NOT_FOUND\", message: \"Connector not found\" });\n }\n\n const isOwner = connector.userId === userId;\n const isGlobal = connector.userId === null;\n\n const hasPermission = permission === \"own\" ? isOwner : isOwner || isGlobal;\n\n if (!hasPermission) {\n throw new TRPCError({\n code: \"FORBIDDEN\",\n message: \"Cannot access this connector\",\n });\n }\n\n return connector;\n};\n\nconst displayConnectorUrl = (value: string): string => {\n const url = new URL(value);\n url.username = \"\";\n url.password = \"\";\n url.search = \"\";\n url.hash = \"\";\n return url.href;\n};\n\ntype McpConnectorRow = NonNullable<\n Awaited<ReturnType<typeof getMcpConnectorById>>\n>;\ntype PublicConnectorInput = Readonly<\n Pick<\n McpConnectorRow,\n | \"enabled\"\n | \"id\"\n | \"name\"\n | \"nameId\"\n | \"requireApproval\"\n | \"type\"\n | \"url\"\n | \"userId\"\n > & {\n createdAt: Readonly<McpConnectorRow[\"createdAt\"]>;\n updatedAt: Readonly<McpConnectorRow[\"updatedAt\"]>;\n }\n>;\n\ntype PublicConnector = {\n -readonly [\n Property in keyof PublicConnectorInput\n ]: PublicConnectorInput[Property];\n} & {\n oauthClientId: null;\n oauthClientSecret: null;\n};\n\nconst publicConnector = (connector: PublicConnectorInput): PublicConnector => ({\n createdAt: connector.createdAt,\n enabled: connector.enabled,\n id: connector.id,\n name: connector.name,\n nameId: connector.nameId,\n oauthClientId: null,\n oauthClientSecret: null,\n requireApproval: connector.requireApproval,\n type: connector.type,\n updatedAt: connector.updatedAt,\n url: displayConnectorUrl(connector.url),\n userId: connector.userId,\n});\n\nexport const mcpRouter = createTRPCRouter({\n /**\n * Initiate OAuth authorization for an MCP connector.\n * Returns the authorization URL that the client should open in a popup.\n */\n authorize: protectedProcedure.input(z.object({ id: z.uuid() })).mutation(\n async ({\n ctx,\n input,\n }: Readonly<{\n ctx: McpProcedureContext;\n input: Readonly<{ id: string }>;\n }>) => {\n assertMcpReady();\n const connector = await getConnectorWithPermission({\n id: input.id,\n permission: \"own-or-global\",\n userId: ctx.user.id,\n });\n\n log.info({ connectorId: connector.id }, \"Initiating OAuth authorization\");\n\n // Remove any existing client to force a fresh connection\n await removeMcpClient(connector.id);\n\n // Create a new client and attempt to connect\n const mcpClient = getOrCreateMcpClient({\n id: connector.id,\n name: connector.name,\n oauthClientId: connector.oauthClientId,\n oauthClientSecret: connector.oauthClientSecret,\n type: connector.type,\n url: connector.url,\n });\n\n await mcpClient.connect();\n\n if (mcpClient.status !== \"authorizing\") {\n throw new TRPCError({\n code: \"BAD_REQUEST\",\n message: \"Connector does not require OAuth authorization\",\n });\n }\n\n const authUrl = mcpClient.getAuthorizationUrl();\n if (!authUrl) {\n throw new TRPCError({\n code: \"INTERNAL_SERVER_ERROR\",\n message: \"Failed to get authorization URL\",\n });\n }\n\n if (authUrl.protocol !== \"http:\" && authUrl.protocol !== \"https:\") {\n throw new TRPCError({\n code: \"BAD_REQUEST\",\n message: \"Invalid authorization URL\",\n });\n }\n log.info(\n { authUrl: authUrl.toString(), connectorId: connector.id },\n \"OAuth authorization URL generated\"\n );\n\n await assertUrlIsSafeToFetch(authUrl.toString(), {\n opaqueErrors: true,\n });\n return { authorizationUrl: authUrl.toString() };\n }\n ),\n\n /**\n * Check if a connector has valid OAuth tokens.\n */\n checkAuth: protectedProcedure.input(z.object({ id: z.uuid() })).query(\n async ({\n ctx,\n input,\n }: Readonly<{\n ctx: McpProcedureContext;\n input: Readonly<{ id: string }>;\n }>) => {\n assertMcpReady();\n const connector = await getConnectorWithPermission({\n id: input.id,\n permission: \"own-or-global\",\n userId: ctx.user.id,\n });\n\n const session = await getAuthenticatedSession({\n mcpConnectorId: connector.id,\n });\n\n return {\n hasSession: Boolean(session),\n isAuthenticated: Boolean(session?.tokens),\n };\n }\n ),\n\n create: protectedProcedure\n .input(\n z.object({\n name: z.string().min(1).max(MCP_NAME_MAX_LENGTH),\n oauthClientId: z.string().optional(),\n oauthClientSecret: z.string().optional(),\n type: z.enum([\"http\", \"sse\"]),\n url: z.url(),\n })\n )\n .mutation(\n async ({\n ctx,\n input,\n }: Readonly<{\n ctx: McpProcedureContext;\n input: Readonly<{\n name: string;\n type: \"http\" | \"sse\";\n url: string;\n oauthClientId?: string | undefined;\n oauthClientSecret?: string | undefined;\n }>;\n }>) => {\n assertMcpReady();\n await assertUrlIsSafeToFetch(input.url, { opaqueErrors: true });\n const nameId = await validateAndGenerateNameId({\n name: input.name,\n userId: ctx.user.id,\n });\n\n return publicConnector(\n await createMcpConnector({\n name: input.name,\n nameId,\n oauthClientId: input.oauthClientId,\n oauthClientSecret: input.oauthClientSecret,\n type: input.type,\n url: input.url,\n userId: ctx.user.id,\n })\n );\n }\n ),\n\n delete: protectedProcedure.input(z.object({ id: z.uuid() })).mutation(\n async ({\n ctx,\n input,\n }: Readonly<{\n ctx: McpProcedureContext;\n input: Readonly<{ id: string }>;\n }>) => {\n assertMcpReady();\n await getConnectorWithPermission({\n id: input.id,\n permission: \"own\",\n userId: ctx.user.id,\n });\n await deleteMcpConnector({ id: input.id });\n await removeMcpClient(input.id);\n return { success: true };\n }\n ),\n\n /**\n * Disconnect an MCP connector by removing OAuth session data only.\n */\n disconnect: protectedProcedure.input(z.object({ id: z.uuid() })).mutation(\n async ({\n ctx,\n input,\n }: Readonly<{\n ctx: McpProcedureContext;\n input: Readonly<{ id: string }>;\n }>) => {\n assertMcpReady();\n await getConnectorWithPermission({\n id: input.id,\n permission: \"own-or-global\",\n userId: ctx.user.id,\n });\n await deleteSessionsByConnectorId({ mcpConnectorId: input.id });\n await removeMcpClient(input.id);\n invalidateAllMcpCaches(input.id);\n return { success: true };\n }\n ),\n\n /**\n * Discover tools, resources, and prompts from an MCP server.\n * Cached for 5 minutes.\n */\n discover: protectedProcedure.input(z.object({ id: z.uuid() })).query(\n async ({\n ctx,\n input,\n }: Readonly<{\n ctx: McpProcedureContext;\n input: Readonly<{ id: string }>;\n }>) => {\n assertMcpReady();\n const connector = await getConnectorWithPermission({\n id: input.id,\n permission: \"own-or-global\",\n userId: ctx.user.id,\n });\n\n const fetchDiscovery = async (): Promise<DiscoveryResult> => {\n log.debug(\n { connectorId: connector.id, url: connector.url },\n \"creating MCP client for discovery (cache miss)\"\n );\n\n // Use OAuth-aware client\n const mcpClient = getOrCreateMcpClient({\n id: connector.id,\n name: connector.name,\n oauthClientId: connector.oauthClientId,\n oauthClientSecret: connector.oauthClientSecret,\n type: connector.type,\n url: connector.url,\n });\n\n await mcpClient.connect();\n\n // Check if authorization is needed\n if (mcpClient.status === \"authorizing\") {\n throw new TRPCError({\n code: \"UNAUTHORIZED\",\n message: \"Connector requires OAuth authorization\",\n });\n }\n\n if (mcpClient.status !== \"connected\") {\n throw new TRPCError({\n code: \"INTERNAL_SERVER_ERROR\",\n message: `Failed to connect to MCP server (status: ${mcpClient.status})`,\n });\n }\n\n log.debug(\n { connectorId: connector.id },\n \"MCP client connected, discovering capabilities\"\n );\n\n try {\n const [toolsResult, resourcesResult, promptsResult] =\n await Promise.all([\n mcpClient\n .tools()\n .then(\n (\n tools: Readonly<\n Record<string, Readonly<{ description?: unknown }>>\n >\n ) =>\n Object.entries(tools).map(\n ([name, tool]: readonly [\n string,\n Readonly<{ description?: unknown }>,\n ]) => ({\n description:\n typeof tool.description === \"string\"\n ? tool.description\n : null,\n name,\n })\n )\n )\n .catch((error: unknown) => {\n log.warn(\n { connectorId: connector.id, err: error },\n \"failed to list tools\"\n );\n return [];\n }),\n mcpClient\n .listResources()\n .then(\n (\n resourceResult: Readonly<{\n resources: readonly McpResourceReader[];\n }>\n ) =>\n resourceResult.resources.map((res: McpResourceReader) => ({\n description: res.description ?? null,\n mimeType: res.mimeType ?? null,\n name: res.name,\n uri: res.uri,\n }))\n )\n .catch((error: unknown) => {\n log.warn(\n { connectorId: connector.id, err: error },\n \"failed to list resources\"\n );\n return [];\n }),\n mcpClient\n .listPrompts()\n .then(\n (\n promptResult: Readonly<{\n prompts: readonly McpPromptReader[];\n }>\n ) =>\n promptResult.prompts.map((prompt: McpPromptReader) => ({\n arguments:\n prompt.arguments?.map(\n (arg: McpPromptArgumentReader) => ({\n description: arg.description ?? null,\n name: arg.name,\n required: arg.required ?? false,\n })\n ) ?? [],\n description: prompt.description ?? null,\n name: prompt.name,\n }))\n )\n .catch((error: unknown) => {\n log.warn(\n { connectorId: connector.id, err: error },\n \"failed to list prompts\"\n );\n return [];\n }),\n ]);\n\n log.info(\n {\n connectorId: connector.id,\n promptsCount: promptsResult.length,\n resourcesCount: resourcesResult.length,\n toolsCount: toolsResult.length,\n },\n \"MCP discovery completed\"\n );\n\n return {\n prompts: promptsResult,\n resources: resourcesResult,\n tools: toolsResult,\n };\n } finally {\n // Don't close the client - keep it cached for reuse\n log.debug({ connectorId: connector.id }, \"MCP discovery finished\");\n }\n };\n\n const cachedFetch = createCachedDiscovery(connector.id, fetchDiscovery);\n\n return await cachedFetch();\n }\n ),\n\n list: protectedProcedure.query(\n async ({\n ctx,\n }: Readonly<{ ctx: McpProcedureContext; input: undefined }>) => {\n assertMcpReady();\n const connectors = await getMcpConnectorsByUserId({\n userId: ctx.user.id,\n });\n return connectors.map((connector: PublicConnectorInput) =>\n publicConnector(connector)\n );\n }\n ),\n\n /**\n * List connectors with their connection status.\n * Returns only connectors that have a valid connection (for use in dropdowns, etc.)\n * Still includes enabled/disabled state so UI can show toggles.\n */\n listConnected: protectedProcedure.query(\n async ({\n ctx,\n }: Readonly<{ ctx: McpProcedureContext; input: undefined }>) => {\n assertMcpReady();\n const connectors = await getMcpConnectorsByUserId({\n userId: ctx.user.id,\n });\n\n const results = await Promise.all(\n connectors.map(async (connector: McpConnectorReader) => {\n const fetchConnectionStatus =\n async (): Promise<ConnectionStatusResult> => {\n const mcpClient = getOrCreateMcpClient({\n id: connector.id,\n name: connector.name,\n oauthClientId: connector.oauthClientId,\n oauthClientSecret: connector.oauthClientSecret,\n type: connector.type,\n url: connector.url,\n });\n const result = await mcpClient.attemptConnection();\n return {\n error: result.error,\n needsAuth: result.needsAuth,\n status: result.status,\n };\n };\n\n const cachedFetch = createCachedConnectionStatus(\n connector.id,\n fetchConnectionStatus\n );\n\n try {\n const status = await cachedFetch();\n return { connector, status };\n } catch {\n return { connector, status: null };\n }\n })\n );\n\n return results\n .filter(\n (connectionResult: McpConnectionResultReader): boolean =>\n connectionResult.status?.status === \"connected\"\n )\n .map((connectionResult: McpConnectionResultReader) =>\n publicConnector(connectionResult.connector)\n );\n }\n ),\n\n /**\n * Refresh/reconnect an MCP client after OAuth completion.\n */\n refreshClient: protectedProcedure.input(z.object({ id: z.uuid() })).mutation(\n async ({\n ctx,\n input,\n }: Readonly<{\n ctx: McpProcedureContext;\n input: Readonly<{ id: string }>;\n }>) => {\n assertMcpReady();\n const connector = await getConnectorWithPermission({\n id: input.id,\n permission: \"own-or-global\",\n userId: ctx.user.id,\n });\n\n await removeMcpClient(connector.id);\n invalidateAllMcpCaches(connector.id);\n\n const mcpClient = getOrCreateMcpClient({\n id: connector.id,\n name: connector.name,\n oauthClientId: connector.oauthClientId,\n oauthClientSecret: connector.oauthClientSecret,\n type: connector.type,\n url: connector.url,\n });\n\n await mcpClient.connect();\n\n return {\n needsAuth: mcpClient.status === \"authorizing\",\n status: mcpClient.status,\n };\n }\n ),\n\n /**\n * Lightweight connection test - just checks if we can connect without full discovery.\n * Much faster than discover since it doesn't fetch tools/resources/prompts.\n * Cached for 60 seconds.\n */\n testConnection: protectedProcedure.input(z.object({ id: z.uuid() })).query(\n async ({\n ctx,\n input,\n }: Readonly<{\n ctx: McpProcedureContext;\n input: Readonly<{ id: string }>;\n }>) => {\n assertMcpReady();\n const connector = await getConnectorWithPermission({\n id: input.id,\n permission: \"own-or-global\",\n userId: ctx.user.id,\n });\n\n const fetchConnectionStatus =\n async (): Promise<ConnectionStatusResult> => {\n log.debug(\n { connectorId: connector.id, url: connector.url },\n \"testing MCP connection (cache miss)\"\n );\n\n const mcpClient = getOrCreateMcpClient({\n id: connector.id,\n name: connector.name,\n oauthClientId: connector.oauthClientId,\n oauthClientSecret: connector.oauthClientSecret,\n type: connector.type,\n url: connector.url,\n });\n\n const result = await mcpClient.attemptConnection();\n\n log.debug(\n {\n connectorId: connector.id,\n error: result.error,\n needsAuth: result.needsAuth,\n status: result.status,\n },\n \"MCP connection test completed\"\n );\n\n return {\n error: result.error,\n needsAuth: result.needsAuth,\n status: result.status,\n };\n };\n\n const cachedFetch = createCachedConnectionStatus(\n connector.id,\n fetchConnectionStatus\n );\n\n return await cachedFetch();\n }\n ),\n\n toggleEnabled: protectedProcedure\n .input(\n z.object({\n enabled: z.boolean(),\n id: z.uuid(),\n })\n )\n .mutation(\n async ({\n ctx,\n input,\n }: Readonly<{\n ctx: McpProcedureContext;\n input: Readonly<{ enabled: boolean; id: string }>;\n }>) => {\n assertMcpReady();\n await getConnectorWithPermission({\n id: input.id,\n permission: \"own\",\n userId: ctx.user.id,\n });\n await updateMcpConnector({\n id: input.id,\n updates: { enabled: input.enabled },\n });\n return { success: true };\n }\n ),\n\n update: protectedProcedure\n .input(\n z.object({\n id: z.uuid(),\n updates: z.object({\n enabled: z.boolean().optional(),\n name: z.string().min(1).max(MCP_NAME_MAX_LENGTH).optional(),\n oauthClientId: z.string().nullable().optional(),\n oauthClientSecret: z.string().nullable().optional(),\n requireApproval: z.boolean().optional(),\n type: z.enum([\"http\", \"sse\"]).optional(),\n url: z.url().optional(),\n }),\n })\n )\n .mutation(\n async ({\n ctx,\n input,\n }: Readonly<{\n ctx: McpProcedureContext;\n input: Readonly<{\n id: string;\n updates: Readonly<{\n enabled?: boolean | undefined;\n name?: string | undefined;\n oauthClientId?: string | null | undefined;\n oauthClientSecret?: string | null | undefined;\n requireApproval?: boolean | undefined;\n type?: \"http\" | \"sse\" | undefined;\n url?: string | undefined;\n }>;\n }>;\n }>) => {\n assertMcpReady();\n const connector = await getConnectorWithPermission({\n id: input.id,\n permission: \"own\",\n userId: ctx.user.id,\n });\n\n const updates: typeof input.updates & { nameId?: string } = {\n ...input.updates,\n };\n if (typeof updates.url === \"string\" && updates.url !== \"\") {\n await assertUrlIsSafeToFetch(updates.url, { opaqueErrors: true });\n }\n if (typeof updates.name === \"string\" && updates.name !== \"\") {\n const nameId = await validateAndGenerateNameId({\n excludeId: input.id,\n name: updates.name,\n userId: connector.userId,\n });\n updates.nameId = nameId;\n }\n\n await updateMcpConnector({ id: input.id, updates });\n if (\n (updates.url !== undefined && updates.url !== connector.url) ||\n (updates.type !== undefined && updates.type !== connector.type) ||\n (updates.oauthClientId !== undefined &&\n updates.oauthClientId !== connector.oauthClientId) ||\n (updates.oauthClientSecret !== undefined &&\n updates.oauthClientSecret !== connector.oauthClientSecret)\n ) {\n await deleteSessionsByConnectorId({ mcpConnectorId: input.id });\n }\n await removeMcpClient(input.id);\n invalidateAllMcpCaches(input.id);\n return { success: true };\n }\n ),\n});\n",
|
|
223
|
+
"type": "registry:file",
|
|
224
|
+
"target": "~/plugins/mcp/router.ts"
|
|
225
|
+
},
|
|
226
|
+
{
|
|
227
|
+
"path": "src/plugins/mcp/src/client-plugin.ts",
|
|
228
|
+
"content": "import type { ChatClientPlugin } from \"@/lib/plugin-contracts\";\nimport { ConnectorsControl } from \"./composer\";\nimport { mcpSettingsItem } from \"./settings\";\n\nexport const mcpClient = () =>\n ({\n id: \"mcp\",\n composerControls: [{ Component: ConnectorsControl, id: \"mcp\" }],\n settingsItems: [mcpSettingsItem],\n }) satisfies ChatClientPlugin;\n",
|
|
229
|
+
"type": "registry:file",
|
|
230
|
+
"target": "~/plugins/mcp/client-plugin.ts"
|
|
231
|
+
},
|
|
232
|
+
{
|
|
233
|
+
"path": "src/plugins/mcp/src/server-plugin.ts",
|
|
234
|
+
"content": "import type { ChatPlugin } from \"@/lib/plugin-contracts\";\nimport { mcpRouter } from \"./router\";\n\nexport const mcp = () =>\n ({ id: \"mcp\", routers: { mcp: mcpRouter } }) satisfies ChatPlugin;\n",
|
|
235
|
+
"type": "registry:file",
|
|
236
|
+
"target": "~/plugins/mcp/server-plugin.ts"
|
|
237
|
+
},
|
|
238
|
+
{
|
|
239
|
+
"path": "dist/source/mcp.json",
|
|
240
|
+
"content": "{\n \"id\": \"mcp\",\n \"kind\": \"plugin\",\n \"files\": [\n \"agent/tools/mcp.ts\",\n \"plugins/mcp/runtime/agent-tools.ts\",\n \"app/(chat)/settings/connectors/page.tsx\",\n \"plugins/mcp/routes/connectors-page.tsx\",\n \"app/(chat)/settings/connectors/[connectorId]/page.tsx\",\n \"plugins/mcp/routes/connector-page.tsx\",\n \"app/api/mcp/oauth/callback/route.ts\",\n \"plugins/mcp/routes/oauth-callback.ts\",\n \"plugins/mcp/ui/connectors-settings.tsx\",\n \"plugins/mcp/ui/connector-header.tsx\",\n \"plugins/mcp/ui/mcp-connect-dialog.tsx\",\n \"plugins/mcp/ui/mcp-create-dialog.tsx\",\n \"plugins/mcp/ui/mcp-details-page.tsx\",\n \"plugins/mcp/composer.tsx\",\n \"plugins/mcp/db/mcp-schema.ts\",\n \"plugins/mcp/db/encrypted-text.ts\",\n \"plugins/mcp/mcp-env.ts\",\n \"plugins/mcp/settings.ts\",\n \"plugins/mcp/setup.ts\",\n \"plugins/mcp/oauth/cache.ts\",\n \"plugins/mcp/oauth/mcp-client-manager.ts\",\n \"plugins/mcp/oauth/mcp-client.ts\",\n \"plugins/mcp/oauth/mcp-fetch.ts\",\n \"plugins/mcp/oauth/mcp-oauth-provider.ts\",\n \"plugins/mcp/oauth/oauth-authorization-required-error.ts\",\n \"plugins/mcp/db/mcp-oauth-lock.ts\",\n \"plugins/mcp/db/mcp-queries.ts\",\n \"plugins/mcp/db/mcp-connector-queries.ts\",\n \"plugins/mcp/db/mcp-oauth-queries.ts\",\n \"plugins/mcp/runtime/mcp-tools.ts\",\n \"plugins/mcp/runtime/mcp-adapter.ts\",\n \"plugins/mcp/search/mcp-search-params.ts\",\n \"plugins/mcp/search/mcp-search-params.server.ts\",\n \"plugins/mcp/router.ts\",\n \"plugins/mcp/client-plugin.ts\",\n \"plugins/mcp/server-plugin.ts\"\n ],\n \"environmentValidation\": \"mcp-env.ts\",\n \"databaseSchemas\": [\"plugins/mcp/db/mcp-schema.ts\"],\n \"envRequirements\": [{ \"options\": [[\"MCP_ENCRYPTION_KEY\"]] }],\n \"server\": { \"export\": \"mcp\", \"routers\": [\"mcp\"] },\n \"client\": {\n \"export\": \"mcpClient\",\n \"composerControls\": [\"mcp\"],\n \"settingsItems\": [\"mcp\"]\n },\n \"contractVersion\": 2,\n \"uiBase\": \"base\"\n}\n",
|
|
241
|
+
"type": "registry:file",
|
|
242
|
+
"target": "~/plugins/mcp/chatjs.json"
|
|
243
|
+
}
|
|
244
|
+
],
|
|
245
|
+
"meta": {
|
|
246
|
+
"chatjs": {
|
|
247
|
+
"id": "mcp",
|
|
248
|
+
"kind": "plugin",
|
|
249
|
+
"files": [
|
|
250
|
+
"agent/tools/mcp.ts",
|
|
251
|
+
"plugins/mcp/runtime/agent-tools.ts",
|
|
252
|
+
"app/(chat)/settings/connectors/page.tsx",
|
|
253
|
+
"plugins/mcp/routes/connectors-page.tsx",
|
|
254
|
+
"app/(chat)/settings/connectors/[connectorId]/page.tsx",
|
|
255
|
+
"plugins/mcp/routes/connector-page.tsx",
|
|
256
|
+
"app/api/mcp/oauth/callback/route.ts",
|
|
257
|
+
"plugins/mcp/routes/oauth-callback.ts",
|
|
258
|
+
"plugins/mcp/ui/connectors-settings.tsx",
|
|
259
|
+
"plugins/mcp/ui/connector-header.tsx",
|
|
260
|
+
"plugins/mcp/ui/mcp-connect-dialog.tsx",
|
|
261
|
+
"plugins/mcp/ui/mcp-create-dialog.tsx",
|
|
262
|
+
"plugins/mcp/ui/mcp-details-page.tsx",
|
|
263
|
+
"plugins/mcp/composer.tsx",
|
|
264
|
+
"plugins/mcp/db/mcp-schema.ts",
|
|
265
|
+
"plugins/mcp/db/encrypted-text.ts",
|
|
266
|
+
"plugins/mcp/mcp-env.ts",
|
|
267
|
+
"plugins/mcp/settings.ts",
|
|
268
|
+
"plugins/mcp/setup.ts",
|
|
269
|
+
"plugins/mcp/oauth/cache.ts",
|
|
270
|
+
"plugins/mcp/oauth/mcp-client-manager.ts",
|
|
271
|
+
"plugins/mcp/oauth/mcp-client.ts",
|
|
272
|
+
"plugins/mcp/oauth/mcp-fetch.ts",
|
|
273
|
+
"plugins/mcp/oauth/mcp-oauth-provider.ts",
|
|
274
|
+
"plugins/mcp/oauth/oauth-authorization-required-error.ts",
|
|
275
|
+
"plugins/mcp/db/mcp-oauth-lock.ts",
|
|
276
|
+
"plugins/mcp/db/mcp-queries.ts",
|
|
277
|
+
"plugins/mcp/db/mcp-connector-queries.ts",
|
|
278
|
+
"plugins/mcp/db/mcp-oauth-queries.ts",
|
|
279
|
+
"plugins/mcp/runtime/mcp-tools.ts",
|
|
280
|
+
"plugins/mcp/runtime/mcp-adapter.ts",
|
|
281
|
+
"plugins/mcp/search/mcp-search-params.ts",
|
|
282
|
+
"plugins/mcp/search/mcp-search-params.server.ts",
|
|
283
|
+
"plugins/mcp/router.ts",
|
|
284
|
+
"plugins/mcp/client-plugin.ts",
|
|
285
|
+
"plugins/mcp/server-plugin.ts"
|
|
286
|
+
],
|
|
287
|
+
"environmentValidation": "mcp-env.ts",
|
|
288
|
+
"databaseSchemas": [
|
|
289
|
+
"plugins/mcp/db/mcp-schema.ts"
|
|
290
|
+
],
|
|
291
|
+
"envRequirements": [
|
|
292
|
+
{
|
|
293
|
+
"options": [
|
|
294
|
+
[
|
|
295
|
+
"MCP_ENCRYPTION_KEY"
|
|
296
|
+
]
|
|
297
|
+
]
|
|
298
|
+
}
|
|
299
|
+
],
|
|
300
|
+
"server": {
|
|
301
|
+
"export": "mcp",
|
|
302
|
+
"routers": [
|
|
303
|
+
"mcp"
|
|
304
|
+
]
|
|
305
|
+
},
|
|
306
|
+
"client": {
|
|
307
|
+
"export": "mcpClient",
|
|
308
|
+
"composerControls": [
|
|
309
|
+
"mcp"
|
|
310
|
+
],
|
|
311
|
+
"settingsItems": [
|
|
312
|
+
"mcp"
|
|
313
|
+
]
|
|
314
|
+
},
|
|
315
|
+
"contractVersion": 2,
|
|
316
|
+
"uiBase": "base"
|
|
317
|
+
}
|
|
318
|
+
},
|
|
319
|
+
"type": "registry:item"
|
|
320
|
+
}
|