@chat-js/registry 0.2.0-beta.8 → 0.2.0-beta.9

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.
Files changed (56) hide show
  1. package/README.md +4 -4
  2. package/dist/r/ai-titles.json +10 -13
  3. package/dist/r/attach-workspace-file.json +1 -1
  4. package/dist/r/attachment-uploads.json +13 -22
  5. package/dist/r/base/ai-titles.json +10 -13
  6. package/dist/r/base/attach-workspace-file.json +1 -1
  7. package/dist/r/base/attachment-uploads.json +13 -22
  8. package/dist/r/base/credits.json +11 -33
  9. package/dist/r/base/desktop.json +14 -30
  10. package/dist/r/base/feedback.json +18 -40
  11. package/dist/r/base/followup-suggestions.json +18 -40
  12. package/dist/r/base/guest-chat.json +19 -34
  13. package/dist/r/base/image-viewer.json +9 -15
  14. package/dist/r/base/mcp.json +23 -46
  15. package/dist/r/base/memory-storage.json +2 -2
  16. package/dist/r/base/model-preferences.json +15 -36
  17. package/dist/r/base/projects.json +23 -45
  18. package/dist/r/base/registry.json +137 -366
  19. package/dist/r/base/search.json +21 -43
  20. package/dist/r/base/sharing.json +18 -40
  21. package/dist/r/base/spreadsheet-viewer.json +9 -15
  22. package/dist/r/base/video-viewer.json +9 -15
  23. package/dist/r/credits.json +11 -33
  24. package/dist/r/desktop.json +14 -30
  25. package/dist/r/feedback.json +18 -40
  26. package/dist/r/followup-suggestions.json +18 -40
  27. package/dist/r/guest-chat.json +19 -34
  28. package/dist/r/image-viewer.json +9 -15
  29. package/dist/r/mcp.json +23 -46
  30. package/dist/r/memory-storage.json +2 -2
  31. package/dist/r/model-preferences.json +15 -36
  32. package/dist/r/projects.json +23 -45
  33. package/dist/r/radix/ai-titles.json +10 -13
  34. package/dist/r/radix/attach-workspace-file.json +1 -1
  35. package/dist/r/radix/attachment-uploads.json +13 -22
  36. package/dist/r/radix/credits.json +11 -33
  37. package/dist/r/radix/desktop.json +14 -30
  38. package/dist/r/radix/feedback.json +18 -40
  39. package/dist/r/radix/followup-suggestions.json +18 -40
  40. package/dist/r/radix/guest-chat.json +19 -34
  41. package/dist/r/radix/image-viewer.json +9 -15
  42. package/dist/r/radix/mcp.json +23 -46
  43. package/dist/r/radix/memory-storage.json +2 -2
  44. package/dist/r/radix/model-preferences.json +15 -36
  45. package/dist/r/radix/projects.json +23 -45
  46. package/dist/r/radix/registry.json +137 -366
  47. package/dist/r/radix/search.json +21 -43
  48. package/dist/r/radix/sharing.json +18 -40
  49. package/dist/r/radix/spreadsheet-viewer.json +9 -15
  50. package/dist/r/radix/video-viewer.json +9 -15
  51. package/dist/r/registry.json +137 -366
  52. package/dist/r/search.json +21 -43
  53. package/dist/r/sharing.json +18 -40
  54. package/dist/r/spreadsheet-viewer.json +9 -15
  55. package/dist/r/video-viewer.json +9 -15
  56. package/package.json +1 -1
package/dist/r/mcp.json CHANGED
@@ -37,7 +37,7 @@
37
37
  "files": [
38
38
  {
39
39
  "path": "src/plugins/mcp/adapters/agent/tools/mcp.ts",
40
- "content": "// ChatJS source: mcp. Ownership: chatjs/plugins/mcp/chatjs.json.\nexport { mcpTools as default } from \"@/chatjs/plugins/mcp/runtime/agent-tools\";\n",
40
+ "content": "// ChatJS source: mcp. Ownership: chatjs/plugins/mcp/plugin.json.\nexport { mcpTools as default } from \"@/chatjs/plugins/mcp/runtime/agent-tools\";\n",
41
41
  "type": "registry:file",
42
42
  "target": "~/agent/tools/mcp.ts"
43
43
  },
@@ -49,7 +49,7 @@
49
49
  },
50
50
  {
51
51
  "path": "src/plugins/mcp/adapters/app/(chat)/settings/connectors/page.tsx",
52
- "content": "// ChatJS source: mcp. Ownership: chatjs/plugins/mcp/chatjs.json.\nimport { ConnectorsSettingsPage } from \"@/chatjs/plugins/mcp/routes/connectors-page\";\n\nconst Page = () => <ConnectorsSettingsPage />;\n\nexport default Page;\n",
52
+ "content": "// ChatJS source: mcp. Ownership: chatjs/plugins/mcp/plugin.json.\nimport { ConnectorsSettingsPage } from \"@/chatjs/plugins/mcp/routes/connectors-page\";\n\nconst Page = () => <ConnectorsSettingsPage />;\n\nexport default Page;\n",
53
53
  "type": "registry:file",
54
54
  "target": "~/app/(chat)/settings/connectors/page.tsx"
55
55
  },
@@ -61,7 +61,7 @@
61
61
  },
62
62
  {
63
63
  "path": "src/plugins/mcp/adapters/app/(chat)/settings/connectors/[connectorId]/page.tsx",
64
- "content": "// ChatJS source: mcp. Ownership: chatjs/plugins/mcp/chatjs.json.\nimport { ConnectorDetailsPage } from \"@/chatjs/plugins/mcp/routes/connector-page\";\n\nconst Page = (props: { readonly params: Promise<{ connectorId: string }> }) => (\n <ConnectorDetailsPage {...props} />\n);\n\nexport default Page;\n",
64
+ "content": "// ChatJS source: mcp. Ownership: chatjs/plugins/mcp/plugin.json.\nimport { ConnectorDetailsPage } from \"@/chatjs/plugins/mcp/routes/connector-page\";\n\nconst Page = (props: { readonly params: Promise<{ connectorId: string }> }) => (\n <ConnectorDetailsPage {...props} />\n);\n\nexport default Page;\n",
65
65
  "type": "registry:file",
66
66
  "target": "~/app/(chat)/settings/connectors/[connectorId]/page.tsx"
67
67
  },
@@ -73,7 +73,7 @@
73
73
  },
74
74
  {
75
75
  "path": "src/plugins/mcp/adapters/app/api/mcp/oauth/callback/route.ts",
76
- "content": "// ChatJS source: mcp. Ownership: chatjs/plugins/mcp/chatjs.json.\nexport { GET } from \"@/chatjs/plugins/mcp/routes/oauth-callback\";\n",
76
+ "content": "// ChatJS source: mcp. Ownership: chatjs/plugins/mcp/plugin.json.\nexport { GET } from \"@/chatjs/plugins/mcp/routes/oauth-callback\";\n",
77
77
  "type": "registry:file",
78
78
  "target": "~/app/api/mcp/oauth/callback/route.ts"
79
79
  },
@@ -139,16 +139,10 @@
139
139
  },
140
140
  {
141
141
  "path": "src/plugins/mcp/src/db/encrypted-text.ts",
142
- "content": "import { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\n\nimport { customType } from \"drizzle-orm/pg-core\";\n\nimport { readMcpEncryptionKey } from \"@/chatjs/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",
142
+ "content": "import { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\n\nimport { customType } from \"drizzle-orm/pg-core\";\n\nimport { readMcpEncryptionKey } from \"@/chatjs/plugins/mcp/validate-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",
143
143
  "type": "registry:file",
144
144
  "target": "~/chatjs/plugins/mcp/db/encrypted-text.ts"
145
145
  },
146
- {
147
- "path": "src/plugins/mcp/src/mcp-env.ts",
148
- "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",
149
- "type": "registry:file",
150
- "target": "~/chatjs/plugins/mcp/mcp-env.ts"
151
- },
152
146
  {
153
147
  "path": "src/plugins/mcp/src/settings.tsx",
154
148
  "content": "\"use client\";\nimport { Plug } from \"lucide-react\";\nimport { SettingsLink } from \"@/components/settings/settings-navigation-link\";\n\nexport const ConnectorsSettingsLink = () => (\n <SettingsLink href=\"/settings/connectors\">\n <Plug className=\"size-4\" />\n Connectors\n </SettingsLink>\n);\n",
@@ -157,10 +151,16 @@
157
151
  },
158
152
  {
159
153
  "path": "src/plugins/mcp/src/setup.ts",
160
- "content": "import descriptor from \"@/chatjs/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",
154
+ "content": "import descriptor from \"@/chatjs/plugins/mcp/plugin.json\";\nimport validateEnvironment from \"./validate-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",
161
155
  "type": "registry:file",
162
156
  "target": "~/chatjs/plugins/mcp/setup.ts"
163
157
  },
158
+ {
159
+ "path": "src/plugins/mcp/src/validate-env.ts",
160
+ "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 };\nexport default validateEnvironment;\n",
161
+ "type": "registry:file",
162
+ "target": "~/chatjs/plugins/mcp/validate-env.ts"
163
+ },
164
164
  {
165
165
  "path": "src/plugins/mcp/src/oauth/cache.ts",
166
166
  "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",
@@ -247,31 +247,27 @@
247
247
  },
248
248
  {
249
249
  "path": "src/plugins/mcp/src/router.ts",
250
- "content": "import type {\n ConnectionStatusResult,\n DiscoveryResult,\n} from \"@/chatjs/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 \"@/chatjs/plugins/mcp/setup\";\nimport {\n createCachedConnectionStatus,\n createCachedDiscovery,\n invalidateAllMcpCaches,\n} from \"@/chatjs/plugins/mcp/oauth/cache\";\nimport {\n getOrCreateMcpClient,\n removeMcpClient,\n} from \"@/chatjs/plugins/mcp/oauth/mcp-client-manager\";\nimport { createModuleLogger } from \"@/lib/logger\";\nimport { installedPlugins } from \"@/integrations/plugin-catalog\";\nimport {\n createMcpConnector,\n deleteMcpConnector,\n deleteSessionsByConnectorId,\n getAuthenticatedSession,\n getMcpConnectorById,\n getMcpConnectorByNameId,\n getMcpConnectorsByUserId,\n updateMcpConnector,\n} from \"@/chatjs/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",
250
+ "content": "import type {\n ConnectionStatusResult,\n DiscoveryResult,\n} from \"@/chatjs/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 \"@/chatjs/plugins/mcp/setup\";\nimport {\n createCachedConnectionStatus,\n createCachedDiscovery,\n invalidateAllMcpCaches,\n} from \"@/chatjs/plugins/mcp/oauth/cache\";\nimport {\n getOrCreateMcpClient,\n removeMcpClient,\n} from \"@/chatjs/plugins/mcp/oauth/mcp-client-manager\";\nimport { createModuleLogger } from \"@/lib/logger\";\nimport { installedPlugins } from \"@/integrations/plugin-catalog\";\nimport {\n createMcpConnector,\n deleteMcpConnector,\n deleteSessionsByConnectorId,\n getAuthenticatedSession,\n getMcpConnectorById,\n getMcpConnectorByNameId,\n getMcpConnectorsByUserId,\n updateMcpConnector,\n} from \"@/chatjs/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\nconst mcpProcedures = {\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\nexport const router = createTRPCRouter({ mcp: mcpProcedures });\n",
251
251
  "type": "registry:file",
252
252
  "target": "~/chatjs/plugins/mcp/router.ts"
253
253
  },
254
254
  {
255
- "path": "src/plugins/mcp/src/client-plugin.ts",
256
- "content": "\"use client\";\nimport { definePlugin, slot } from \"@/chatjs/core/ui/slots\";\nimport { ComposerExtensions, SettingsLinks } from \"@/components/chat-slots\";\nimport { ConnectorsControl } from \"./composer\";\nimport { ConnectorsSettingsLink } from \"./settings\";\n\nexport const mcpClient = definePlugin({\n id: \"mcp\",\n slots: [\n slot(ComposerExtensions, ConnectorsControl),\n slot(SettingsLinks, ConnectorsSettingsLink),\n ],\n});\n",
255
+ "path": "src/plugins/mcp/src/chat-ui.ts",
256
+ "content": "\"use client\";\nimport { definePlugin, slot } from \"@/chatjs/core/ui/slots\";\nimport { ComposerExtensions, SettingsLinks } from \"@/components/chat-slots\";\nimport { ConnectorsControl } from \"./composer\";\nimport { ConnectorsSettingsLink } from \"./settings\";\n\nexport const chatUi = definePlugin({\n id: \"mcp\",\n slots: [\n slot(ComposerExtensions, ConnectorsControl),\n slot(SettingsLinks, ConnectorsSettingsLink),\n ],\n});\n",
257
257
  "type": "registry:file",
258
- "target": "~/chatjs/plugins/mcp/client-plugin.ts"
259
- },
260
- {
261
- "path": "src/plugins/mcp/src/server-plugin.ts",
262
- "content": "import type { ChatPlugin } from \"@/chatjs/core/installation/plugin\";\nimport { mcpRouter } from \"./router\";\n\nexport const mcp = () =>\n ({ id: \"mcp\", routers: { mcp: mcpRouter } }) satisfies ChatPlugin;\n",
263
- "type": "registry:file",
264
- "target": "~/chatjs/plugins/mcp/server-plugin.ts"
258
+ "target": "~/chatjs/plugins/mcp/chat-ui.ts"
265
259
  },
266
260
  {
267
261
  "path": "dist/source/mcp.json",
268
- "content": "{\n \"id\": \"mcp\",\n \"kind\": \"plugin\",\n \"files\": [\n \"agent/tools/mcp.ts\",\n \"chatjs/plugins/mcp/runtime/agent-tools.ts\",\n \"app/(chat)/settings/connectors/page.tsx\",\n \"chatjs/plugins/mcp/routes/connectors-page.tsx\",\n \"app/(chat)/settings/connectors/[connectorId]/page.tsx\",\n \"chatjs/plugins/mcp/routes/connector-page.tsx\",\n \"app/api/mcp/oauth/callback/route.ts\",\n \"chatjs/plugins/mcp/routes/oauth-callback.ts\",\n \"chatjs/plugins/mcp/ui/connectors-settings.tsx\",\n \"chatjs/plugins/mcp/ui/connector-header.tsx\",\n \"chatjs/plugins/mcp/ui/mcp-connect-dialog.tsx\",\n \"chatjs/plugins/mcp/ui/mcp-create-dialog.tsx\",\n \"chatjs/plugins/mcp/ui/transport-select.tsx\",\n \"chatjs/plugins/mcp/ui/mcp-details-page.tsx\",\n \"chatjs/plugins/mcp/composer.tsx\",\n \"chatjs/plugins/mcp/connector-menu-item.tsx\",\n \"chatjs/plugins/mcp/db/mcp-schema.ts\",\n \"chatjs/plugins/mcp/db/encrypted-text.ts\",\n \"chatjs/plugins/mcp/mcp-env.ts\",\n \"chatjs/plugins/mcp/settings.tsx\",\n \"chatjs/plugins/mcp/setup.ts\",\n \"chatjs/plugins/mcp/oauth/cache.ts\",\n \"chatjs/plugins/mcp/oauth/mcp-client-manager.ts\",\n \"chatjs/plugins/mcp/oauth/mcp-client.ts\",\n \"chatjs/plugins/mcp/oauth/mcp-fetch.ts\",\n \"chatjs/plugins/mcp/oauth/mcp-oauth-provider.ts\",\n \"chatjs/plugins/mcp/oauth/oauth-authorization-required-error.ts\",\n \"chatjs/plugins/mcp/db/mcp-oauth-lock.ts\",\n \"chatjs/plugins/mcp/db/mcp-queries.ts\",\n \"chatjs/plugins/mcp/db/mcp-connector-queries.ts\",\n \"chatjs/plugins/mcp/db/mcp-oauth-queries.ts\",\n \"chatjs/plugins/mcp/runtime/mcp-tools.ts\",\n \"chatjs/plugins/mcp/runtime/mcp-adapter.ts\",\n \"chatjs/plugins/mcp/search/mcp-search-params.ts\",\n \"chatjs/plugins/mcp/search/mcp-search-params.server.ts\",\n \"chatjs/plugins/mcp/router.ts\",\n \"chatjs/plugins/mcp/client-plugin.ts\",\n \"chatjs/plugins/mcp/server-plugin.ts\"\n ],\n \"environmentValidation\": \"mcp-env.ts\",\n \"databaseSchemas\": [\"chatjs/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",
262
+ "content": "{\n \"contractVersion\": 3,\n \"uiBase\": \"base\",\n \"id\": \"mcp\",\n \"kind\": \"plugin\",\n \"files\": [\n \"agent/tools/mcp.ts\",\n \"chatjs/plugins/mcp/runtime/agent-tools.ts\",\n \"app/(chat)/settings/connectors/page.tsx\",\n \"chatjs/plugins/mcp/routes/connectors-page.tsx\",\n \"app/(chat)/settings/connectors/[connectorId]/page.tsx\",\n \"chatjs/plugins/mcp/routes/connector-page.tsx\",\n \"app/api/mcp/oauth/callback/route.ts\",\n \"chatjs/plugins/mcp/routes/oauth-callback.ts\",\n \"chatjs/plugins/mcp/ui/connectors-settings.tsx\",\n \"chatjs/plugins/mcp/ui/connector-header.tsx\",\n \"chatjs/plugins/mcp/ui/mcp-connect-dialog.tsx\",\n \"chatjs/plugins/mcp/ui/mcp-create-dialog.tsx\",\n \"chatjs/plugins/mcp/ui/transport-select.tsx\",\n \"chatjs/plugins/mcp/ui/mcp-details-page.tsx\",\n \"chatjs/plugins/mcp/composer.tsx\",\n \"chatjs/plugins/mcp/connector-menu-item.tsx\",\n \"chatjs/plugins/mcp/db/mcp-schema.ts\",\n \"chatjs/plugins/mcp/db/encrypted-text.ts\",\n \"chatjs/plugins/mcp/settings.tsx\",\n \"chatjs/plugins/mcp/setup.ts\",\n \"chatjs/plugins/mcp/validate-env.ts\",\n \"chatjs/plugins/mcp/oauth/cache.ts\",\n \"chatjs/plugins/mcp/oauth/mcp-client-manager.ts\",\n \"chatjs/plugins/mcp/oauth/mcp-client.ts\",\n \"chatjs/plugins/mcp/oauth/mcp-fetch.ts\",\n \"chatjs/plugins/mcp/oauth/mcp-oauth-provider.ts\",\n \"chatjs/plugins/mcp/oauth/oauth-authorization-required-error.ts\",\n \"chatjs/plugins/mcp/db/mcp-oauth-lock.ts\",\n \"chatjs/plugins/mcp/db/mcp-queries.ts\",\n \"chatjs/plugins/mcp/db/mcp-connector-queries.ts\",\n \"chatjs/plugins/mcp/db/mcp-oauth-queries.ts\",\n \"chatjs/plugins/mcp/runtime/mcp-tools.ts\",\n \"chatjs/plugins/mcp/runtime/mcp-adapter.ts\",\n \"chatjs/plugins/mcp/search/mcp-search-params.ts\",\n \"chatjs/plugins/mcp/search/mcp-search-params.server.ts\",\n \"chatjs/plugins/mcp/router.ts\",\n \"chatjs/plugins/mcp/chat-ui.ts\"\n ],\n \"databaseSchemas\": [\"chatjs/plugins/mcp/db/mcp-schema.ts\"],\n \"envRequirements\": [{ \"options\": [[\"MCP_ENCRYPTION_KEY\"]] }]\n}\n",
269
263
  "type": "registry:file",
270
- "target": "~/chatjs/plugins/mcp/chatjs.json"
264
+ "target": "~/chatjs/plugins/mcp/plugin.json"
271
265
  }
272
266
  ],
273
267
  "meta": {
274
268
  "chatjs": {
269
+ "contractVersion": 3,
270
+ "uiBase": "base",
275
271
  "id": "mcp",
276
272
  "kind": "plugin",
277
273
  "files": [
@@ -293,9 +289,9 @@
293
289
  "chatjs/plugins/mcp/connector-menu-item.tsx",
294
290
  "chatjs/plugins/mcp/db/mcp-schema.ts",
295
291
  "chatjs/plugins/mcp/db/encrypted-text.ts",
296
- "chatjs/plugins/mcp/mcp-env.ts",
297
292
  "chatjs/plugins/mcp/settings.tsx",
298
293
  "chatjs/plugins/mcp/setup.ts",
294
+ "chatjs/plugins/mcp/validate-env.ts",
299
295
  "chatjs/plugins/mcp/oauth/cache.ts",
300
296
  "chatjs/plugins/mcp/oauth/mcp-client-manager.ts",
301
297
  "chatjs/plugins/mcp/oauth/mcp-client.ts",
@@ -311,10 +307,8 @@
311
307
  "chatjs/plugins/mcp/search/mcp-search-params.ts",
312
308
  "chatjs/plugins/mcp/search/mcp-search-params.server.ts",
313
309
  "chatjs/plugins/mcp/router.ts",
314
- "chatjs/plugins/mcp/client-plugin.ts",
315
- "chatjs/plugins/mcp/server-plugin.ts"
310
+ "chatjs/plugins/mcp/chat-ui.ts"
316
311
  ],
317
- "environmentValidation": "mcp-env.ts",
318
312
  "databaseSchemas": [
319
313
  "chatjs/plugins/mcp/db/mcp-schema.ts"
320
314
  ],
@@ -326,24 +320,7 @@
326
320
  ]
327
321
  ]
328
322
  }
329
- ],
330
- "server": {
331
- "export": "mcp",
332
- "routers": [
333
- "mcp"
334
- ]
335
- },
336
- "client": {
337
- "export": "mcpClient",
338
- "composerControls": [
339
- "mcp"
340
- ],
341
- "settingsItems": [
342
- "mcp"
343
- ]
344
- },
345
- "contractVersion": 2,
346
- "uiBase": "base"
323
+ ]
347
324
  }
348
325
  },
349
326
  "type": "registry:item"
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
3
  "name": "memory-storage",
4
- "title": "In-Memory",
5
- "description": "In-memory store backed by a Map - the test/reference adapter. Zero dependencies, isomorphic (no node:fs), and non-persistent: everything is lost when the process exits. Ideal for unit tests; not for production.",
4
+ "title": "No persistent storage",
5
+ "description": "Files are temporary and disappear when the server restarts.",
6
6
  "dependencies": [
7
7
  "files-sdk@2.5.0"
8
8
  ],
@@ -16,10 +16,10 @@
16
16
  "target": "~/chatjs/plugins/model-preferences/apply-model-preferences.ts"
17
17
  },
18
18
  {
19
- "path": "src/plugins/model-preferences/src/client-plugin.ts",
20
- "content": "\"use client\";\nimport { definePlugin, slot } from \"@/chatjs/core/ui/slots\";\nimport { ModelSettingsLink } from \"@/components/chat-slots\";\nimport { ModelPreferencesLink } from \"./settings-link\";\nimport { useModelPreferences } from \"./use-model-preferences\";\n\nexport const modelPreferencesClient = definePlugin({\n id: \"model-preferences\",\n slots: [slot(ModelSettingsLink, ModelPreferencesLink)],\n useModelVisibility: useModelPreferences,\n});\n",
19
+ "path": "src/plugins/model-preferences/src/chat-ui.ts",
20
+ "content": "\"use client\";\nimport { definePlugin, slot } from \"@/chatjs/core/ui/slots\";\nimport { ModelSettingsLink } from \"@/components/chat-slots\";\nimport { ModelPreferencesLink } from \"./settings-link\";\n\nexport const chatUi = definePlugin({\n id: \"model-preferences\",\n slots: [slot(ModelSettingsLink, ModelPreferencesLink)],\n});\n",
21
21
  "type": "registry:file",
22
- "target": "~/chatjs/plugins/model-preferences/client-plugin.ts"
22
+ "target": "~/chatjs/plugins/model-preferences/chat-ui.ts"
23
23
  },
24
24
  {
25
25
  "path": "src/plugins/model-preferences/src/settings-link.tsx",
@@ -65,42 +65,38 @@
65
65
  },
66
66
  {
67
67
  "path": "src/plugins/model-preferences/src/router.ts",
68
- "content": "import { z } from \"zod\";\n\nimport {\n getUserModelPreferences,\n upsertUserModelPreference,\n} from \"./model-preferences-queries\";\n\nimport { createTRPCRouter, protectedProcedure } from \"@/trpc/init\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\n\nexport const modelPreferencesRouter = createTRPCRouter({\n getModelPreferences: protectedProcedure.query(\n async ({\n ctx,\n }: {\n readonly ctx: { readonly user: { readonly id: string } };\n }) => await getUserModelPreferences({ userId: ctx.user.id })\n ),\n\n setModelEnabled: protectedProcedure\n .input(\n z.object({\n enabled: z.boolean(),\n modelId: z.string(),\n })\n )\n .mutation(\n async ({\n ctx,\n input,\n }: {\n readonly ctx: { readonly user: { readonly id: string } };\n readonly input: ReadonlyNativeSurface<{\n enabled: boolean;\n modelId: string;\n }>;\n }) => {\n await upsertUserModelPreference({\n enabled: input.enabled,\n modelId: input.modelId,\n userId: ctx.user.id,\n });\n return { success: true };\n }\n ),\n});\n",
68
+ "content": "import { z } from \"zod\";\n\nimport {\n getUserModelPreferences,\n upsertUserModelPreference,\n} from \"./model-preferences-queries\";\n\nimport { createTRPCRouter, protectedProcedure } from \"@/trpc/init\";\nimport type { ReadonlyNativeSurface } from \"@/lib/readonly-native-surface\";\n\nconst modelPreferencesProcedures = {\n getModelPreferences: protectedProcedure.query(\n async ({\n ctx,\n }: {\n readonly ctx: { readonly user: { readonly id: string } };\n }) => await getUserModelPreferences({ userId: ctx.user.id })\n ),\n\n setModelEnabled: protectedProcedure\n .input(\n z.object({\n enabled: z.boolean(),\n modelId: z.string(),\n })\n )\n .mutation(\n async ({\n ctx,\n input,\n }: {\n readonly ctx: { readonly user: { readonly id: string } };\n readonly input: ReadonlyNativeSurface<{\n enabled: boolean;\n modelId: string;\n }>;\n }) => {\n await upsertUserModelPreference({\n enabled: input.enabled,\n modelId: input.modelId,\n userId: ctx.user.id,\n });\n return { success: true };\n }\n ),\n};\n\nexport const router = createTRPCRouter({\n modelPreferences: modelPreferencesProcedures,\n});\n",
69
69
  "type": "registry:file",
70
70
  "target": "~/chatjs/plugins/model-preferences/router.ts"
71
71
  },
72
72
  {
73
- "path": "src/plugins/model-preferences/src/server-plugin.ts",
74
- "content": "import type { ChatPlugin } from \"@/chatjs/core/installation/plugin\";\nimport { modelPreferencesRouter } from \"./router\";\n\nexport const modelPreferences = () =>\n ({\n id: \"model-preferences\",\n routers: { modelPreferences: modelPreferencesRouter },\n }) satisfies ChatPlugin;\n",
73
+ "path": "src/plugins/model-preferences/src/model-visibility.ts",
74
+ "content": "\"use client\";\n\nimport { useMemo } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useSession } from \"@/providers/session-provider\";\nimport { useTRPC } from \"@/trpc/react\";\nimport { applyModelPreferences } from \"./apply-model-preferences\";\n\nexport const useModelVisibility = (\n defaults: ReadonlySet<string>\n): ReadonlySet<string> => {\n const trpc = useTRPC();\n const { data: session } = useSession();\n const authenticated = Boolean(session?.user);\n const { data: preferences } = useQuery({\n ...trpc.modelPreferences.getModelPreferences.queryOptions(),\n enabled: authenticated,\n });\n return useMemo(\n () =>\n authenticated && preferences\n ? applyModelPreferences(defaults, preferences)\n : defaults,\n [authenticated, defaults, preferences]\n );\n};\n",
75
75
  "type": "registry:file",
76
- "target": "~/chatjs/plugins/model-preferences/server-plugin.ts"
77
- },
78
- {
79
- "path": "src/plugins/model-preferences/src/use-model-preferences.ts",
80
- "content": "\"use client\";\n\nimport { useMemo } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useSession } from \"@/providers/session-provider\";\nimport { useTRPC } from \"@/trpc/react\";\nimport { applyModelPreferences } from \"./apply-model-preferences\";\n\nexport const useModelPreferences = (\n defaults: ReadonlySet<string>\n): ReadonlySet<string> => {\n const trpc = useTRPC();\n const { data: session } = useSession();\n const authenticated = Boolean(session?.user);\n const { data: preferences } = useQuery({\n ...trpc.modelPreferences.getModelPreferences.queryOptions(),\n enabled: authenticated,\n });\n return useMemo(\n () =>\n authenticated && preferences\n ? applyModelPreferences(defaults, preferences)\n : defaults,\n [authenticated, defaults, preferences]\n );\n};\n",
81
- "type": "registry:file",
82
- "target": "~/chatjs/plugins/model-preferences/use-model-preferences.ts"
76
+ "target": "~/chatjs/plugins/model-preferences/model-visibility.ts"
83
77
  },
84
78
  {
85
79
  "path": "src/plugins/model-preferences/adapters/app/(chat)/settings/models/page.tsx",
86
- "content": "// ChatJS source: model-preferences. Ownership: chatjs/plugins/model-preferences/chatjs.json.\nexport { ModelsSettingsPage as default } from \"@/chatjs/plugins/model-preferences/models-page\";\n",
80
+ "content": "// ChatJS source: model-preferences. Ownership: chatjs/plugins/model-preferences/plugin.json.\nexport { ModelsSettingsPage as default } from \"@/chatjs/plugins/model-preferences/models-page\";\n",
87
81
  "type": "registry:file",
88
82
  "target": "~/app/(chat)/settings/models/page.tsx"
89
83
  },
90
84
  {
91
85
  "path": "dist/source/model-preferences.json",
92
- "content": "{\n \"id\": \"model-preferences\",\n \"kind\": \"plugin\",\n \"files\": [\n \"chatjs/plugins/model-preferences/apply-model-preferences.ts\",\n \"chatjs/plugins/model-preferences/client-plugin.ts\",\n \"chatjs/plugins/model-preferences/settings-link.tsx\",\n \"chatjs/plugins/model-preferences/model-preferences-queries.ts\",\n \"chatjs/plugins/model-preferences/model-preferences-schema.ts\",\n \"chatjs/plugins/model-preferences/model-row.tsx\",\n \"chatjs/plugins/model-preferences/models-page.tsx\",\n \"chatjs/plugins/model-preferences/models-settings.tsx\",\n \"chatjs/plugins/model-preferences/models-table.tsx\",\n \"chatjs/plugins/model-preferences/router.ts\",\n \"chatjs/plugins/model-preferences/server-plugin.ts\",\n \"chatjs/plugins/model-preferences/use-model-preferences.ts\",\n \"app/(chat)/settings/models/page.tsx\"\n ],\n \"databaseSchemas\": [\n \"chatjs/plugins/model-preferences/model-preferences-schema.ts\"\n ],\n \"server\": { \"export\": \"modelPreferences\", \"routers\": [\"modelPreferences\"] },\n \"client\": {\n \"export\": \"modelPreferencesClient\",\n \"composerControls\": [],\n \"settingsItems\": [\"models\"],\n \"modelVisibility\": true\n },\n \"contractVersion\": 2,\n \"uiBase\": \"base\"\n}\n",
86
+ "content": "{\n \"contractVersion\": 3,\n \"uiBase\": \"base\",\n \"id\": \"model-preferences\",\n \"kind\": \"plugin\",\n \"files\": [\n \"chatjs/plugins/model-preferences/apply-model-preferences.ts\",\n \"chatjs/plugins/model-preferences/chat-ui.ts\",\n \"chatjs/plugins/model-preferences/settings-link.tsx\",\n \"chatjs/plugins/model-preferences/model-preferences-queries.ts\",\n \"chatjs/plugins/model-preferences/model-preferences-schema.ts\",\n \"chatjs/plugins/model-preferences/model-row.tsx\",\n \"chatjs/plugins/model-preferences/models-page.tsx\",\n \"chatjs/plugins/model-preferences/models-settings.tsx\",\n \"chatjs/plugins/model-preferences/models-table.tsx\",\n \"chatjs/plugins/model-preferences/router.ts\",\n \"chatjs/plugins/model-preferences/model-visibility.ts\",\n \"app/(chat)/settings/models/page.tsx\"\n ],\n \"databaseSchemas\": [\n \"chatjs/plugins/model-preferences/model-preferences-schema.ts\"\n ]\n}\n",
93
87
  "type": "registry:file",
94
- "target": "~/chatjs/plugins/model-preferences/chatjs.json"
88
+ "target": "~/chatjs/plugins/model-preferences/plugin.json"
95
89
  }
96
90
  ],
97
91
  "meta": {
98
92
  "chatjs": {
93
+ "contractVersion": 3,
94
+ "uiBase": "base",
99
95
  "id": "model-preferences",
100
96
  "kind": "plugin",
101
97
  "files": [
102
98
  "chatjs/plugins/model-preferences/apply-model-preferences.ts",
103
- "chatjs/plugins/model-preferences/client-plugin.ts",
99
+ "chatjs/plugins/model-preferences/chat-ui.ts",
104
100
  "chatjs/plugins/model-preferences/settings-link.tsx",
105
101
  "chatjs/plugins/model-preferences/model-preferences-queries.ts",
106
102
  "chatjs/plugins/model-preferences/model-preferences-schema.ts",
@@ -109,29 +105,12 @@
109
105
  "chatjs/plugins/model-preferences/models-settings.tsx",
110
106
  "chatjs/plugins/model-preferences/models-table.tsx",
111
107
  "chatjs/plugins/model-preferences/router.ts",
112
- "chatjs/plugins/model-preferences/server-plugin.ts",
113
- "chatjs/plugins/model-preferences/use-model-preferences.ts",
108
+ "chatjs/plugins/model-preferences/model-visibility.ts",
114
109
  "app/(chat)/settings/models/page.tsx"
115
110
  ],
116
111
  "databaseSchemas": [
117
112
  "chatjs/plugins/model-preferences/model-preferences-schema.ts"
118
- ],
119
- "server": {
120
- "export": "modelPreferences",
121
- "routers": [
122
- "modelPreferences"
123
- ]
124
- },
125
- "client": {
126
- "export": "modelPreferencesClient",
127
- "composerControls": [],
128
- "settingsItems": [
129
- "models"
130
- ],
131
- "modelVisibility": true
132
- },
133
- "contractVersion": 2,
134
- "uiBase": "base"
113
+ ]
135
114
  }
136
115
  },
137
116
  "type": "registry:item"