|
| 1 | +import { z } from 'zod' |
| 2 | + |
| 3 | +import { |
| 4 | + LIBRARY_BY_INSTANCE, |
| 5 | + resolveLibraries, |
| 6 | + StackSearchQueryParam, |
| 7 | + toPublicLibrary, |
| 8 | +} from '../types/stack.types' |
| 9 | + |
| 10 | +import type { McpRegistrationContext } from '@repo/mcp-common/src/registration-context' |
| 11 | +import type { AiSearchChunk, AiSearchNamespace } from '../stack-mcp.context' |
| 12 | +import type { StackLibrary } from '../types/stack.types' |
| 13 | + |
| 14 | +const MAX_RESULTS = 10 |
| 15 | + |
| 16 | +interface RequiredEnv { |
| 17 | + AI_SEARCH: AiSearchNamespace |
| 18 | +} |
| 19 | + |
| 20 | +function formatError(message: string) { |
| 21 | + return { content: [{ type: 'text' as const, text: `Error: ${message}` }], isError: true } |
| 22 | +} |
| 23 | + |
| 24 | +function toResult(chunk: AiSearchChunk, fallback?: StackLibrary) { |
| 25 | + const lib = chunk.instance_id ? LIBRARY_BY_INSTANCE.get(chunk.instance_id) : fallback |
| 26 | + const title = |
| 27 | + typeof chunk.item.metadata?.title === 'string' ? chunk.item.metadata.title : chunk.item.key |
| 28 | + return { |
| 29 | + url: chunk.item.key, |
| 30 | + title, |
| 31 | + text: chunk.text, |
| 32 | + score: chunk.score, |
| 33 | + library: lib?.name ?? 'docs', |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | + * Registers the Developer Stack tools for one request. The stack is scoped to the |
| 39 | + * subset selected via the `?libs=` URL param (or the whole stack when unscoped), |
| 40 | + * read from the request URL so both `/mcp` and `/sse` honor it. |
| 41 | + */ |
| 42 | +export function registerStackTools<Env extends RequiredEnv>(context: McpRegistrationContext<Env>) { |
| 43 | + const env = context.env |
| 44 | + const libsParam = new URL(context.request.url).searchParams.get('libs') |
| 45 | + const allowed = resolveLibraries(libsParam) |
| 46 | + |
| 47 | + const allowedSlugs = allowed.map((l) => l.slug) as [string, ...string[]] |
| 48 | + const allowedIds = allowed.map((l) => l.instanceId) |
| 49 | + const bySlug = new Map(allowed.map((l) => [l.slug, l])) |
| 50 | + const names = allowed.map((l) => l.name).join(', ') |
| 51 | + |
| 52 | + context.registerTool( |
| 53 | + 'list_libraries', |
| 54 | + { |
| 55 | + description: `List the tools whose documentation this server can search (${names}), with each one's slug, name, source site, and a short description. |
| 56 | +
|
| 57 | +Use it to check whether a tool is covered, or to get the exact \`library\` slug for search_docs. You do not need to call it first: searching without a \`library\` already covers the whole stack.`, |
| 58 | + inputSchema: z.object({}), |
| 59 | + outputSchema: z.object({ |
| 60 | + libraries: z.array( |
| 61 | + z.object({ |
| 62 | + slug: z.string(), |
| 63 | + name: z.string(), |
| 64 | + source: z.string(), |
| 65 | + description: z.string(), |
| 66 | + }) |
| 67 | + ), |
| 68 | + }), |
| 69 | + annotations: { title: 'List developer-stack libraries', readOnlyHint: true }, |
| 70 | + }, |
| 71 | + async () => { |
| 72 | + const libraries = allowed.map(toPublicLibrary) |
| 73 | + return { |
| 74 | + structuredContent: { libraries }, |
| 75 | + content: [ |
| 76 | + { |
| 77 | + type: 'text' as const, |
| 78 | + text: allowed |
| 79 | + .map((l) => `- ${l.slug}: ${l.name} (${l.source}). ${l.description}`) |
| 80 | + .join('\n'), |
| 81 | + }, |
| 82 | + ], |
| 83 | + } |
| 84 | + } |
| 85 | + ) |
| 86 | + |
| 87 | + context.registerTool( |
| 88 | + 'search_docs', |
| 89 | + { |
| 90 | + description: `Search current documentation for the tools in this developer stack (${names}) and get back the most relevant excerpts, each with a source link. |
| 91 | +
|
| 92 | +Reach for this whenever you are answering a question about, or writing code that uses, any of these tools. They change often, so your built-in knowledge of their APIs, configuration, and defaults is frequently out of date. Retrieve the docs instead of relying on memory, and ground the code you generate in what you find. |
| 93 | +
|
| 94 | +Cite the returned source URLs in your answer. Searches the whole stack by default; set \`library\` to one slug (from list_libraries) to focus on a single tool.`, |
| 95 | + inputSchema: z.object({ |
| 96 | + query: StackSearchQueryParam, |
| 97 | + library: z |
| 98 | + .enum(allowedSlugs) |
| 99 | + .optional() |
| 100 | + .describe( |
| 101 | + 'Optional. Restrict the search to a single library by its slug (from list_libraries). Omit to search the whole stack, which is usually best unless you already know the exact tool.' |
| 102 | + ), |
| 103 | + }), |
| 104 | + outputSchema: z.object({ |
| 105 | + results: z.array( |
| 106 | + z.object({ |
| 107 | + url: z.string(), |
| 108 | + title: z.string(), |
| 109 | + text: z.string(), |
| 110 | + score: z.number(), |
| 111 | + library: z.string(), |
| 112 | + }) |
| 113 | + ), |
| 114 | + }), |
| 115 | + annotations: { title: 'Search developer-stack docs', readOnlyHint: true }, |
| 116 | + }, |
| 117 | + async ({ query, library }) => { |
| 118 | + try { |
| 119 | + const retrieval = { max_num_results: MAX_RESULTS } |
| 120 | + // Reranking is always on: it re-orders retrieved chunks for relevance. |
| 121 | + const reranking = { enabled: true } |
| 122 | + let results: Array<ReturnType<typeof toResult>> |
| 123 | + |
| 124 | + if (library) { |
| 125 | + const lib = bySlug.get(library) |
| 126 | + if (!lib) return formatError(`Unknown library: ${library}`) |
| 127 | + const res = await env.AI_SEARCH.get(lib.instanceId).search({ |
| 128 | + query, |
| 129 | + ai_search_options: { retrieval, reranking }, |
| 130 | + }) |
| 131 | + results = res.chunks.map((c) => toResult(c, lib)) |
| 132 | + } else { |
| 133 | + const res = await env.AI_SEARCH.search({ |
| 134 | + query, |
| 135 | + ai_search_options: { instance_ids: allowedIds, retrieval, reranking }, |
| 136 | + }) |
| 137 | + results = res.chunks.map((c) => toResult(c)) |
| 138 | + } |
| 139 | + |
| 140 | + const text = |
| 141 | + results.length === 0 |
| 142 | + ? 'No relevant documentation found.' |
| 143 | + : results |
| 144 | + .map( |
| 145 | + (r) => |
| 146 | + `<result>\n<library>${r.library}</library>\n<url>${r.url}</url>\n<title>${r.title}</title>\n<text>\n${r.text}\n</text>\n</result>` |
| 147 | + ) |
| 148 | + .join('\n') |
| 149 | + |
| 150 | + return { structuredContent: { results }, content: [{ type: 'text' as const, text }] } |
| 151 | + } catch (e) { |
| 152 | + return formatError(e instanceof Error ? e.message : String(e)) |
| 153 | + } |
| 154 | + } |
| 155 | + ) |
| 156 | +} |
0 commit comments