|
1 | 1 | // Entry point for the MCP server
|
2 | 2 | import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
3 | 3 | import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
| 4 | +import escapeStringRegexp from 'escape-string-regexp'; |
4 | 5 | import { z } from 'zod';
|
| 6 | +import { listRepos, search, getFileSource } from './client.js'; |
5 | 7 | import { env, numberSchema } from './env.js';
|
6 |
| -import { listRepositoriesResponseSchema, searchResponseSchema } from './schemas.js'; |
7 |
| -import { ListRepositoriesResponse, SearchRequest, SearchResponse, TextContent, ServiceError } from './types.js'; |
| 8 | +import { TextContent } from './types.js'; |
8 | 9 | import { base64Decode, isServiceError } from './utils.js';
|
9 |
| -import escapeStringRegexp from 'escape-string-regexp'; |
10 | 10 |
|
11 | 11 | // Create MCP server
|
12 | 12 | const server = new McpServer({
|
13 | 13 | name: 'sourcebot-mcp-server',
|
14 | 14 | version: '0.1.0',
|
15 | 15 | });
|
16 | 16 |
|
| 17 | + |
17 | 18 | server.tool(
|
18 | 19 | "search_code",
|
19 |
| - `Fetches code snippets that match the given keywords exactly. This is not a semantic search. Results are returned as an array of files, where each file contains a list of code snippets, as well as the file's URL, repository, and language. ALWAYS include the file's external URL when referencing a file.`, |
| 20 | + `Fetches code that matches the provided regex pattern in \`query\`. This is NOT a semantic search. |
| 21 | + Results are returned as an array of matching files, with the file's URL, repository, and language. |
| 22 | + If the \`includeCodeSnippets\` property is true, code snippets containing the matches will be included in the response. Only set this to true if the request requires code snippets (e.g., show me examples where library X is used). |
| 23 | + When referencing a file in your response, **ALWAYS** include the file's external URL as a link. This makes it easier for the user to view the file, even if they don't have it locally checked out. |
| 24 | + **ONLY USE** the \`filterByRepoIds\` property if the request requires searching a specific repo(s). Otherwise, leave it empty.`, |
20 | 25 | {
|
21 | 26 | query: z
|
22 | 27 | .string()
|
23 | 28 | .describe(`The regex pattern to search for. RULES:
|
24 |
| - 1. When a regex special character needs to be escaped, ALWAYS use a single backslash (\) (e.g., 'console\.log') |
25 |
| - 2. ALWAYS escape spaces with a single backslash (\) (e.g., 'console\ log') |
| 29 | + 1. When a regex special character needs to be escaped, ALWAYS use a single backslash (\) (e.g., 'console\.log') |
| 30 | + 2. **ALWAYS** escape spaces with a single backslash (\) (e.g., 'console\ log') |
26 | 31 | `),
|
27 |
| - repoIds: z |
| 32 | + filterByRepoIds: z |
28 | 33 | .array(z.string())
|
29 |
| - .describe(`Scope the search to the provided repositories to the Sourcebot compatible repository IDs. Do not use this property if you want to search all repositories. You must call 'list_repos' first to obtain the exact repository ID.`) |
| 34 | + .describe(`Scope the search to the provided repositories to the Sourcebot compatible repository IDs. **DO NOT** use this property if you want to search all repositories. **YOU MUST** call 'list_repos' first to obtain the exact repository ID.`) |
30 | 35 | .optional(),
|
31 |
| - languages: z |
| 36 | + filterByLanguages: z |
32 | 37 | .array(z.string())
|
33 | 38 | .describe(`Scope the search to the provided languages. The language MUST be formatted as a GitHub linguist language. Examples: Python, JavaScript, TypeScript, Java, C#, C++, PHP, Go, Rust, Ruby, Swift, Kotlin, Shell, C, Dart, HTML, CSS, PowerShell, SQL, R`)
|
34 | 39 | .optional(),
|
| 40 | + caseSensitive: z |
| 41 | + .boolean() |
| 42 | + .describe(`Whether the search should be case sensitive (default: false).`) |
| 43 | + .optional(), |
| 44 | + includeCodeSnippets: z |
| 45 | + .boolean() |
| 46 | + .describe(`Whether to include the code snippets in the response (default: false). If false, only the file's URL, repository, and language will be returned. Set to false to get a more concise response.`) |
| 47 | + .optional(), |
35 | 48 | maxTokens: numberSchema
|
36 | 49 | .describe(`The maximum number of tokens to return (default: ${env.DEFAULT_MINIMUM_TOKENS}). Higher values provide more context but consume more tokens. Values less than ${env.DEFAULT_MINIMUM_TOKENS} will be ignored.`)
|
37 | 50 | .transform((val) => (val < env.DEFAULT_MINIMUM_TOKENS ? env.DEFAULT_MINIMUM_TOKENS : val))
|
38 | 51 | .optional(),
|
39 |
| - caseSensitive: z.boolean() |
40 |
| - .describe(`Whether the search should be case sensitive (default: false).`) |
41 |
| - .optional(), |
42 | 52 | },
|
43 | 53 | async ({
|
44 | 54 | query,
|
45 |
| - repoIds = [], |
46 |
| - languages = [], |
| 55 | + filterByRepoIds: repoIds = [], |
| 56 | + filterByLanguages: languages = [], |
47 | 57 | maxTokens = env.DEFAULT_MINIMUM_TOKENS,
|
| 58 | + includeCodeSnippets = false, |
48 | 59 | caseSensitive = false,
|
49 | 60 | }) => {
|
50 | 61 | if (repoIds.length > 0) {
|
@@ -96,12 +107,16 @@ server.tool(
|
96 | 107 | const content = base64Decode(chunk.content);
|
97 | 108 | return `\`\`\`\n${content}\n\`\`\``
|
98 | 109 | }).join('\n');
|
99 |
| - const text = `file: ${file.url}\nrepository: ${file.repository}\nlanguage: ${file.language}\n${snippets}`; |
| 110 | + const numMatches = file.chunks.reduce( |
| 111 | + (acc, chunk) => acc + chunk.matchRanges.length, |
| 112 | + 0, |
| 113 | + ); |
| 114 | + const text = `file: ${file.url}\nnum_matches: ${numMatches}\nrepository: ${file.repository}\nlanguage: ${file.language}\n${includeCodeSnippets ? `snippets:\n${snippets}` : ''}`; |
100 | 115 | // Rough estimate of the number of tokens in the text
|
101 | 116 | // @see: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them
|
102 | 117 | const tokens = text.length / 4;
|
103 | 118 |
|
104 |
| - if ((totalTokens + tokens) > (maxTokens ?? env.DEFAULT_MINIMUM_TOKENS)) { |
| 119 | + if ((totalTokens + tokens) > maxTokens) { |
105 | 120 | isResponseTruncated = true;
|
106 | 121 | break;
|
107 | 122 | }
|
@@ -153,39 +168,40 @@ server.tool(
|
153 | 168 | }
|
154 | 169 | );
|
155 | 170 |
|
156 |
| -const search = async (request: SearchRequest): Promise<SearchResponse | ServiceError> => { |
157 |
| - console.error(`Executing search request: ${JSON.stringify(request, null, 2)}`); |
158 |
| - const result = await fetch(`${env.SOURCEBOT_HOST}/api/search`, { |
159 |
| - method: 'POST', |
160 |
| - headers: { |
161 |
| - 'Content-Type': 'application/json', |
162 |
| - 'X-Org-Domain': '~' |
163 |
| - }, |
164 |
| - body: JSON.stringify(request) |
165 |
| - }).then(response => response.json()); |
166 |
| - |
167 |
| - if (isServiceError(result)) { |
168 |
| - return result; |
169 |
| - } |
| 171 | +server.tool( |
| 172 | + "get_file_source", |
| 173 | + "Fetches the source code for a given file.", |
| 174 | + { |
| 175 | + fileName: z.string().describe("The file to fetch the source code for."), |
| 176 | + repository: z.string().describe("The repository to fetch the source code for. This is the Sourcebot compatible repository ID."), |
| 177 | + }, |
| 178 | + async ({ fileName, repository }) => { |
| 179 | + const response = await getFileSource({ |
| 180 | + fileName, |
| 181 | + repository, |
| 182 | + }); |
170 | 183 |
|
171 |
| - return searchResponseSchema.parse(result); |
172 |
| -} |
| 184 | + if (isServiceError(response)) { |
| 185 | + return { |
| 186 | + content: [{ |
| 187 | + type: "text", |
| 188 | + text: `Error fetching file source: ${response.message}`, |
| 189 | + }], |
| 190 | + }; |
| 191 | + } |
173 | 192 |
|
174 |
| -const listRepos = async (): Promise<ListRepositoriesResponse | ServiceError> => { |
175 |
| - const result = await fetch(`${env.SOURCEBOT_HOST}/api/repos`, { |
176 |
| - method: 'GET', |
177 |
| - headers: { |
178 |
| - 'Content-Type': 'application/json', |
179 |
| - 'X-Org-Domain': '~' |
180 |
| - }, |
181 |
| - }).then(response => response.json()); |
182 |
| - |
183 |
| - if (isServiceError(result)) { |
184 |
| - return result; |
| 193 | + const content: TextContent[] = [{ |
| 194 | + type: "text", |
| 195 | + text: `file: ${fileName}\nrepository: ${repository}\nlanguage: ${response.language}\nsource:\n${base64Decode(response.source)}`, |
| 196 | + }] |
| 197 | + |
| 198 | + return { |
| 199 | + content, |
| 200 | + }; |
185 | 201 | }
|
| 202 | +); |
| 203 | + |
186 | 204 |
|
187 |
| - return listRepositoriesResponseSchema.parse(result); |
188 |
| -} |
189 | 205 |
|
190 | 206 | const runServer = async () => {
|
191 | 207 | const transport = new StdioServerTransport();
|
|
0 commit comments