catalog.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import { Client } from "@modelcontextprotocol/sdk/client/index.js"
  2. import {
  3. CallToolResultSchema,
  4. ListToolsResultSchema,
  5. ToolSchema,
  6. type Tool as MCPToolDef,
  7. } from "@modelcontextprotocol/sdk/types.js"
  8. import { dynamicTool, jsonSchema, type JSONSchema7, type Tool } from "ai"
  9. import { Effect } from "effect"
  10. const DEFAULT_TIMEOUT = 30_000
  11. const MAX_LIST_PAGES = 1_000
  12. const TolerantListToolsResultSchema = ListToolsResultSchema.extend({
  13. tools: ToolSchema.omit({ outputSchema: true }).array(),
  14. })
  15. export async function paginate<T, R extends { nextCursor?: string }>(
  16. list: (cursor?: string) => Promise<R>,
  17. items: (result: R) => T[],
  18. ) {
  19. const result: T[] = []
  20. const cursors = new Set<string>()
  21. let cursor: string | undefined
  22. for (let page = 0; page < MAX_LIST_PAGES; page++) {
  23. const page = await list(cursor)
  24. result.push(...items(page))
  25. if (page.nextCursor === undefined) return result
  26. if (cursors.has(page.nextCursor)) throw new Error(`MCP list returned duplicate cursor: ${page.nextCursor}`)
  27. cursors.add(page.nextCursor)
  28. cursor = page.nextCursor
  29. }
  30. throw new Error(`MCP list exceeded ${MAX_LIST_PAGES} pages`)
  31. }
  32. export function defs(client: Client, timeout?: number) {
  33. return listTools(client, timeout ?? DEFAULT_TIMEOUT).pipe(Effect.catch(() => Effect.void))
  34. }
  35. export function convertTool(mcpTool: MCPToolDef, client: Client, timeout?: number): Tool {
  36. const inputSchema: JSONSchema7 = {
  37. ...(mcpTool.inputSchema as JSONSchema7),
  38. type: "object",
  39. properties: (mcpTool.inputSchema.properties ?? {}) as JSONSchema7["properties"],
  40. additionalProperties: false,
  41. }
  42. return dynamicTool({
  43. description: mcpTool.description ?? "",
  44. inputSchema: jsonSchema(inputSchema),
  45. execute: async (args: unknown, options) => {
  46. const result = await client.callTool(
  47. {
  48. name: mcpTool.name,
  49. arguments: (args || {}) as Record<string, unknown>,
  50. },
  51. CallToolResultSchema,
  52. {
  53. resetTimeoutOnProgress: true,
  54. signal: options.abortSignal,
  55. timeout,
  56. // The MCP SDK only sends a progress token when this hook is present, enabling timeout resets.
  57. onprogress: () => {},
  58. },
  59. )
  60. if (result.isError)
  61. throw new Error(
  62. result.content
  63. .flatMap((item) => (item.type === "text" ? [item.text] : []))
  64. .filter((text) => text.trim())
  65. .join("\n\n") || "MCP tool returned an error",
  66. )
  67. if (result.structuredContent === undefined || result.structuredContent === null) return result
  68. return {
  69. ...result,
  70. content: [{ type: "text" as const, text: JSON.stringify(result.structuredContent) }],
  71. }
  72. },
  73. })
  74. }
  75. export function fetch<T extends { name: string }>(
  76. clientName: string,
  77. client: Client,
  78. list: (client: Client) => Promise<T[]>,
  79. label: string,
  80. ) {
  81. return Effect.tryPromise({
  82. try: () => list(client),
  83. catch: (error) => error,
  84. }).pipe(
  85. Effect.tapError((error) =>
  86. Effect.logWarning(`failed to get ${label}`, {
  87. clientName,
  88. error: error instanceof Error ? error.message : String(error),
  89. }),
  90. ),
  91. Effect.map((items) => {
  92. const sanitizedClient = sanitize(clientName)
  93. return Object.fromEntries(
  94. items.map((item) => [sanitizedClient + ":" + sanitize(item.name), { ...item, client: clientName }]),
  95. )
  96. }),
  97. Effect.orElseSucceed(() => undefined),
  98. )
  99. }
  100. export const sanitize = (value: string) => value.replace(/[^a-zA-Z0-9_-]/g, "_")
  101. export function prompts(client: Client, timeout?: number) {
  102. if (!client.getServerCapabilities()?.prompts) return Promise.resolve([])
  103. return paginate(
  104. (cursor) => client.listPrompts(cursor === undefined ? undefined : { cursor }, { timeout }),
  105. (result) => result.prompts,
  106. )
  107. }
  108. export function resources(client: Client, timeout?: number) {
  109. if (!client.getServerCapabilities()?.resources) return Promise.resolve([])
  110. return paginate(
  111. (cursor) => client.listResources(cursor === undefined ? undefined : { cursor }, { timeout }),
  112. (result) => result.resources,
  113. )
  114. }
  115. function listTools(client: Client, timeout: number) {
  116. return Effect.tryPromise({
  117. try: () =>
  118. paginate(
  119. async (cursor) => {
  120. const params = cursor === undefined ? undefined : { cursor }
  121. try {
  122. return await client.listTools(params, { timeout })
  123. } catch (error) {
  124. if (!(error instanceof Error) || !isOutputSchemaValidationError(error)) throw error
  125. return client.request({ method: "tools/list", params }, TolerantListToolsResultSchema, { timeout })
  126. }
  127. },
  128. (result) => result.tools,
  129. ),
  130. catch: (error) => (error instanceof Error ? error : new Error(String(error))),
  131. })
  132. }
  133. function isOutputSchemaValidationError(error: Error) {
  134. return /can't resolve reference|resolves to more than one schema|outputSchema|schema.*reference|reference.*schema/i.test(
  135. error.message,
  136. )
  137. }
  138. export * as McpCatalog from "./catalog"