@sourcebot/mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,4 @@
1
+ # @sourcebot/mcp
2
+
3
+ MCP (Model Context Protocol) server for Sourcebot.
4
+
@@ -0,0 +1,4 @@
1
+ import { FileSourceRequest, FileSourceResponse, ListRepositoriesResponse, SearchRequest, SearchResponse, ServiceError } from './types.js';
2
+ export declare const search: (request: SearchRequest) => Promise<SearchResponse | ServiceError>;
3
+ export declare const listRepos: () => Promise<ListRepositoriesResponse | ServiceError>;
4
+ export declare const getFileSource: (request: FileSourceRequest) => Promise<FileSourceResponse | ServiceError>;
package/dist/client.js ADDED
@@ -0,0 +1,46 @@
1
+ import { env } from './env.js';
2
+ import { listRepositoriesResponseSchema, searchResponseSchema, fileSourceResponseSchema } from './schemas.js';
3
+ import { isServiceError } from './utils.js';
4
+ export const search = async (request) => {
5
+ console.error(`Executing search request: ${JSON.stringify(request, null, 2)}`);
6
+ const result = await fetch(`${env.SOURCEBOT_HOST}/api/search`, {
7
+ method: 'POST',
8
+ headers: {
9
+ 'Content-Type': 'application/json',
10
+ 'X-Org-Domain': '~'
11
+ },
12
+ body: JSON.stringify(request)
13
+ }).then(response => response.json());
14
+ if (isServiceError(result)) {
15
+ return result;
16
+ }
17
+ return searchResponseSchema.parse(result);
18
+ };
19
+ export const listRepos = async () => {
20
+ const result = await fetch(`${env.SOURCEBOT_HOST}/api/repos`, {
21
+ method: 'GET',
22
+ headers: {
23
+ 'Content-Type': 'application/json',
24
+ 'X-Org-Domain': '~'
25
+ },
26
+ }).then(response => response.json());
27
+ if (isServiceError(result)) {
28
+ return result;
29
+ }
30
+ return listRepositoriesResponseSchema.parse(result);
31
+ };
32
+ export const getFileSource = async (request) => {
33
+ const result = await fetch(`${env.SOURCEBOT_HOST}/api/source`, {
34
+ method: 'POST',
35
+ headers: {
36
+ 'Content-Type': 'application/json',
37
+ 'X-Org-Domain': '~'
38
+ },
39
+ body: JSON.stringify(request)
40
+ }).then(response => response.json());
41
+ if (isServiceError(result)) {
42
+ return result;
43
+ }
44
+ return fileSourceResponseSchema.parse(result);
45
+ };
46
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC/B,OAAO,EAAE,8BAA8B,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AAE9G,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAE5C,MAAM,CAAC,MAAM,MAAM,GAAG,KAAK,EAAE,OAAsB,EAA0C,EAAE;IAC3F,OAAO,CAAC,KAAK,CAAC,6BAA6B,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;IAC/E,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,GAAG,GAAG,CAAC,cAAc,aAAa,EAAE;QAC3D,MAAM,EAAE,MAAM;QACd,OAAO,EAAE;YACL,cAAc,EAAE,kBAAkB;YAClC,cAAc,EAAE,GAAG;SACtB;QACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;KAChC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;IAErC,IAAI,cAAc,CAAC,MAAM,CAAC,EAAE,CAAC;QACzB,OAAO,MAAM,CAAC;IAClB,CAAC;IAED,OAAO,oBAAoB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AAC9C,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,SAAS,GAAG,KAAK,IAAsD,EAAE;IAClF,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,GAAG,GAAG,CAAC,cAAc,YAAY,EAAE;QAC1D,MAAM,EAAE,KAAK;QACb,OAAO,EAAE;YACL,cAAc,EAAE,kBAAkB;YAClC,cAAc,EAAE,GAAG;SACtB;KACJ,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;IAErC,IAAI,cAAc,CAAC,MAAM,CAAC,EAAE,CAAC;QACzB,OAAO,MAAM,CAAC;IAClB,CAAC;IAED,OAAO,8BAA8B,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AACxD,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,aAAa,GAAG,KAAK,EAAE,OAA0B,EAA8C,EAAE;IAC1G,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,GAAG,GAAG,CAAC,cAAc,aAAa,EAAE;QAC3D,MAAM,EAAE,MAAM;QACd,OAAO,EAAE;YACL,cAAc,EAAE,kBAAkB;YAClC,cAAc,EAAE,GAAG;SACtB;QACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;KAChC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;IAErC,IAAI,cAAc,CAAC,MAAM,CAAC,EAAE,CAAC;QACzB,OAAO,MAAM,CAAC;IAClB,CAAC;IAED,OAAO,wBAAwB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AAClD,CAAC,CAAA","sourcesContent":["import { env } from './env.js';\nimport { listRepositoriesResponseSchema, searchResponseSchema, fileSourceResponseSchema } from './schemas.js';\nimport { FileSourceRequest, FileSourceResponse, ListRepositoriesResponse, SearchRequest, SearchResponse, ServiceError } from './types.js';\nimport { isServiceError } from './utils.js';\n\nexport const search = async (request: SearchRequest): Promise<SearchResponse | ServiceError> => {\n console.error(`Executing search request: ${JSON.stringify(request, null, 2)}`);\n const result = await fetch(`${env.SOURCEBOT_HOST}/api/search`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-Org-Domain': '~'\n },\n body: JSON.stringify(request)\n }).then(response => response.json());\n\n if (isServiceError(result)) {\n return result;\n }\n\n return searchResponseSchema.parse(result);\n}\n\nexport const listRepos = async (): Promise<ListRepositoriesResponse | ServiceError> => {\n const result = await fetch(`${env.SOURCEBOT_HOST}/api/repos`, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n 'X-Org-Domain': '~'\n },\n }).then(response => response.json());\n\n if (isServiceError(result)) {\n return result;\n }\n\n return listRepositoriesResponseSchema.parse(result);\n}\n\nexport const getFileSource = async (request: FileSourceRequest): Promise<FileSourceResponse | ServiceError> => {\n const result = await fetch(`${env.SOURCEBOT_HOST}/api/source`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-Org-Domain': '~'\n },\n body: JSON.stringify(request)\n }).then(response => response.json());\n\n if (isServiceError(result)) {\n return result;\n }\n\n return fileSourceResponseSchema.parse(result);\n}\n"]}
package/dist/env.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { z } from "zod";
2
+ export declare const numberSchema: z.ZodNumber;
3
+ export declare const env: Readonly<{
4
+ SOURCEBOT_HOST: string;
5
+ DEFAULT_MINIMUM_TOKENS: number;
6
+ DEFAULT_MATCHES: number;
7
+ DEFAULT_CONTEXT_LINES: number;
8
+ }>;
package/dist/env.js ADDED
@@ -0,0 +1,17 @@
1
+ import { createEnv } from "@t3-oss/env-core";
2
+ import { z } from "zod";
3
+ export const numberSchema = z.coerce.number();
4
+ export const env = createEnv({
5
+ server: {
6
+ SOURCEBOT_HOST: z.string().url().default("http://localhost:3000"),
7
+ // The minimum number of tokens to return
8
+ DEFAULT_MINIMUM_TOKENS: numberSchema.default(10000),
9
+ // The number of matches to fetch from the search API.
10
+ DEFAULT_MATCHES: numberSchema.default(10000),
11
+ // The number of lines to include above and below a match
12
+ DEFAULT_CONTEXT_LINES: numberSchema.default(5),
13
+ },
14
+ runtimeEnv: process.env,
15
+ emptyStringAsUndefined: true,
16
+ });
17
+ //# sourceMappingURL=env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.js","sourceRoot":"","sources":["../src/env.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;AAE9C,MAAM,CAAC,MAAM,GAAG,GAAG,SAAS,CAAC;IACzB,MAAM,EAAE;QACJ,cAAc,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAAC;QAEjE,yCAAyC;QACzC,sBAAsB,EAAE,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC;QAEnD,sDAAsD;QACtD,eAAe,EAAE,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC;QAE5C,yDAAyD;QACzD,qBAAqB,EAAE,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC;KACjD;IACD,UAAU,EAAE,OAAO,CAAC,GAAG;IACvB,sBAAsB,EAAE,IAAI;CAC/B,CAAC,CAAC","sourcesContent":["import { createEnv } from \"@t3-oss/env-core\";\nimport { z } from \"zod\";\n\nexport const numberSchema = z.coerce.number();\n\nexport const env = createEnv({\n server: {\n SOURCEBOT_HOST: z.string().url().default(\"http://localhost:3000\"),\n\n // The minimum number of tokens to return\n DEFAULT_MINIMUM_TOKENS: numberSchema.default(10000),\n\n // The number of matches to fetch from the search API.\n DEFAULT_MATCHES: numberSchema.default(10000),\n\n // The number of lines to include above and below a match\n DEFAULT_CONTEXT_LINES: numberSchema.default(5),\n },\n runtimeEnv: process.env,\n emptyStringAsUndefined: true,\n});"]}
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,169 @@
1
+ // Entry point for the MCP server
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import escapeStringRegexp from 'escape-string-regexp';
5
+ import { z } from 'zod';
6
+ import { listRepos, search, getFileSource } from './client.js';
7
+ import { env, numberSchema } from './env.js';
8
+ import { base64Decode, isServiceError } from './utils.js';
9
+ // Create MCP server
10
+ const server = new McpServer({
11
+ name: 'sourcebot-mcp-server',
12
+ version: '0.1.0',
13
+ });
14
+ server.tool("search_code", `Fetches code that matches the provided regex pattern in \`query\`. This is NOT a semantic search.
15
+ Results are returned as an array of matching files, with the file's URL, repository, and language.
16
+ 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).
17
+ 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.
18
+ **ONLY USE** the \`filterByRepoIds\` property if the request requires searching a specific repo(s). Otherwise, leave it empty.`, {
19
+ query: z
20
+ .string()
21
+ .describe(`The regex pattern to search for. RULES:
22
+ 1. When a regex special character needs to be escaped, ALWAYS use a single backslash (\) (e.g., 'console\.log')
23
+ 2. **ALWAYS** escape spaces with a single backslash (\) (e.g., 'console\ log')
24
+ `),
25
+ filterByRepoIds: z
26
+ .array(z.string())
27
+ .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.`)
28
+ .optional(),
29
+ filterByLanguages: z
30
+ .array(z.string())
31
+ .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`)
32
+ .optional(),
33
+ caseSensitive: z
34
+ .boolean()
35
+ .describe(`Whether the search should be case sensitive (default: false).`)
36
+ .optional(),
37
+ includeCodeSnippets: z
38
+ .boolean()
39
+ .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.`)
40
+ .optional(),
41
+ maxTokens: numberSchema
42
+ .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.`)
43
+ .transform((val) => (val < env.DEFAULT_MINIMUM_TOKENS ? env.DEFAULT_MINIMUM_TOKENS : val))
44
+ .optional(),
45
+ }, async ({ query, filterByRepoIds: repoIds = [], filterByLanguages: languages = [], maxTokens = env.DEFAULT_MINIMUM_TOKENS, includeCodeSnippets = false, caseSensitive = false, }) => {
46
+ if (repoIds.length > 0) {
47
+ query += ` ( repo:${repoIds.map(id => escapeStringRegexp(id)).join(' or repo:')} )`;
48
+ }
49
+ if (languages.length > 0) {
50
+ query += ` ( lang:${languages.join(' or lang:')} )`;
51
+ }
52
+ if (caseSensitive) {
53
+ query += ` case:yes`;
54
+ }
55
+ else {
56
+ query += ` case:no`;
57
+ }
58
+ console.error(`Executing search request: ${query}`);
59
+ const response = await search({
60
+ query,
61
+ matches: env.DEFAULT_MATCHES,
62
+ contextLines: env.DEFAULT_CONTEXT_LINES,
63
+ });
64
+ if (isServiceError(response)) {
65
+ return {
66
+ content: [{
67
+ type: "text",
68
+ text: `Error searching code: ${response.message}`,
69
+ }],
70
+ };
71
+ }
72
+ if (response.files.length === 0) {
73
+ return {
74
+ content: [{
75
+ type: "text",
76
+ text: `No results found for the query: ${query}`,
77
+ }],
78
+ };
79
+ }
80
+ const content = [];
81
+ let totalTokens = 0;
82
+ let isResponseTruncated = false;
83
+ for (const file of response.files) {
84
+ const numMatches = file.chunks.reduce((acc, chunk) => acc + chunk.matchRanges.length, 0);
85
+ let text = `file: ${file.url}\nnum_matches: ${numMatches}\nrepository: ${file.repository}\nlanguage: ${file.language}`;
86
+ if (includeCodeSnippets) {
87
+ const snippets = file.chunks.map(chunk => {
88
+ const content = base64Decode(chunk.content);
89
+ return `\`\`\`\n${content}\n\`\`\``;
90
+ }).join('\n');
91
+ text += `\n\n${snippets}`;
92
+ }
93
+ // Rough estimate of the number of tokens in the text
94
+ // @see: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them
95
+ const tokens = text.length / 4;
96
+ if ((totalTokens + tokens) > maxTokens) {
97
+ isResponseTruncated = true;
98
+ break;
99
+ }
100
+ totalTokens += tokens;
101
+ content.push({
102
+ type: "text",
103
+ text,
104
+ });
105
+ }
106
+ if (isResponseTruncated) {
107
+ content.push({
108
+ type: "text",
109
+ text: `The response was truncated because the number of tokens exceeded the maximum limit of ${maxTokens}.`,
110
+ });
111
+ }
112
+ return {
113
+ content,
114
+ };
115
+ });
116
+ server.tool("list_repos", "Lists all repositories in the organization.", async () => {
117
+ const response = await listRepos();
118
+ if (isServiceError(response)) {
119
+ return {
120
+ content: [{
121
+ type: "text",
122
+ text: `Error listing repositories: ${response.message}`,
123
+ }],
124
+ };
125
+ }
126
+ const content = response.repos.map(repo => {
127
+ return {
128
+ type: "text",
129
+ text: `id: ${repo.name}\nurl: ${repo.url}`,
130
+ };
131
+ });
132
+ return {
133
+ content,
134
+ };
135
+ });
136
+ server.tool("get_file_source", "Fetches the source code for a given file.", {
137
+ fileName: z.string().describe("The file to fetch the source code for."),
138
+ repository: z.string().describe("The repository to fetch the source code for. This is the Sourcebot compatible repository ID."),
139
+ }, async ({ fileName, repository }) => {
140
+ const response = await getFileSource({
141
+ fileName,
142
+ repository,
143
+ });
144
+ if (isServiceError(response)) {
145
+ return {
146
+ content: [{
147
+ type: "text",
148
+ text: `Error fetching file source: ${response.message}`,
149
+ }],
150
+ };
151
+ }
152
+ const content = [{
153
+ type: "text",
154
+ text: `file: ${fileName}\nrepository: ${repository}\nlanguage: ${response.language}\nsource:\n${base64Decode(response.source)}`,
155
+ }];
156
+ return {
157
+ content,
158
+ };
159
+ });
160
+ const runServer = async () => {
161
+ const transport = new StdioServerTransport();
162
+ await server.connect(transport);
163
+ console.error('Sourcebot MCP server ready');
164
+ };
165
+ runServer().catch((error) => {
166
+ console.error('Failed to start MCP server:', error);
167
+ process.exit(1);
168
+ });
169
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,iCAAiC;AACjC,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,kBAAkB,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,EAAE,GAAG,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAE1D,oBAAoB;AACpB,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC;IACzB,IAAI,EAAE,sBAAsB;IAC5B,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAGH,MAAM,CAAC,IAAI,CACP,aAAa,EACb;;;;mIAI+H,EAC/H;IACI,KAAK,EAAE,CAAC;SACH,MAAM,EAAE;SACR,QAAQ,CAAC;;;SAGb,CAAC;IACF,eAAe,EAAE,CAAC;SACb,KAAK,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;SACjB,QAAQ,CAAC,wOAAwO,CAAC;SAClP,QAAQ,EAAE;IACf,iBAAiB,EAAE,CAAC;SACf,KAAK,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;SACjB,QAAQ,CAAC,sPAAsP,CAAC;SAChQ,QAAQ,EAAE;IACf,aAAa,EAAE,CAAC;SACX,OAAO,EAAE;SACT,QAAQ,CAAC,+DAA+D,CAAC;SACzE,QAAQ,EAAE;IACf,mBAAmB,EAAE,CAAC;SACjB,OAAO,EAAE;SACT,QAAQ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C,wCAAwC,CAAC;IACvE,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,8FAA8F,CAAC;CAClI,EACD,KAAK,EAAE,EAAE,QAAQ,EAAE,UAAU,EAAE,EAAE,EAAE;IAC/B,MAAM,QAAQ,GAAG,MAAM,aAAa,CAAC;QACjC,QAAQ;QACR,UAAU;KACb,CAAC,CAAC;IAEH,IAAI,cAAc,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC3B,OAAO;YACH,OAAO,EAAE,CAAC;oBACN,IAAI,EAAE,MAAM;oBACZ,IAAI,EAAE,+BAA+B,QAAQ,CAAC,OAAO,EAAE;iBAC1D,CAAC;SACL,CAAC;IACN,CAAC;IAED,MAAM,OAAO,GAAkB,CAAC;YAC5B,IAAI,EAAE,MAAM;YACZ,IAAI,EAAE,SAAS,QAAQ,iBAAiB,UAAU,eAAe,QAAQ,CAAC,QAAQ,cAAc,YAAY,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;SAClI,CAAC,CAAA;IAEF,OAAO;QACH,OAAO;KACV,CAAC;AACN,CAAC,CACJ,CAAC;AAIF,MAAM,SAAS,GAAG,KAAK,IAAI,EAAE;IACzB,MAAM,SAAS,GAAG,IAAI,oBAAoB,EAAE,CAAC;IAC7C,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO,CAAC,KAAK,CAAC,4BAA4B,CAAC,CAAC;AAChD,CAAC,CAAA;AAED,SAAS,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACxB,OAAO,CAAC,KAAK,CAAC,6BAA6B,EAAE,KAAK,CAAC,CAAC;IACpD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC","sourcesContent":["// Entry point for the MCP server\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport escapeStringRegexp from 'escape-string-regexp';\nimport { z } from 'zod';\nimport { listRepos, search, getFileSource } from './client.js';\nimport { env, numberSchema } from './env.js';\nimport { TextContent } from './types.js';\nimport { base64Decode, isServiceError } from './utils.js';\n\n// Create MCP server\nconst server = new McpServer({\n name: 'sourcebot-mcp-server',\n version: '0.1.0',\n});\n\n\nserver.tool(\n \"search_code\",\n `Fetches code that matches the provided regex pattern in \\`query\\`. This is NOT a semantic search.\n Results are returned as an array of matching files, with the file's URL, repository, and language.\n 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).\n 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.\n **ONLY USE** the \\`filterByRepoIds\\` property if the request requires searching a specific repo(s). Otherwise, leave it empty.`,\n {\n query: z\n .string()\n .describe(`The regex pattern to search for. RULES:\n 1. When a regex special character needs to be escaped, ALWAYS use a single backslash (\\) (e.g., 'console\\.log')\n 2. **ALWAYS** escape spaces with a single backslash (\\) (e.g., 'console\\ log')\n `),\n filterByRepoIds: z\n .array(z.string())\n .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.`)\n .optional(),\n filterByLanguages: z\n .array(z.string())\n .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`)\n .optional(),\n caseSensitive: z\n .boolean()\n .describe(`Whether the search should be case sensitive (default: false).`)\n .optional(),\n includeCodeSnippets: z\n .boolean()\n .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.`)\n .optional(),\n maxTokens: numberSchema\n .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.`)\n .transform((val) => (val < env.DEFAULT_MINIMUM_TOKENS ? env.DEFAULT_MINIMUM_TOKENS : val))\n .optional(),\n },\n async ({\n query,\n filterByRepoIds: repoIds = [],\n filterByLanguages: languages = [],\n maxTokens = env.DEFAULT_MINIMUM_TOKENS,\n includeCodeSnippets = false,\n caseSensitive = false,\n }) => {\n if (repoIds.length > 0) {\n query += ` ( repo:${repoIds.map(id => escapeStringRegexp(id)).join(' or repo:')} )`;\n }\n\n if (languages.length > 0) {\n query += ` ( lang:${languages.join(' or lang:')} )`;\n }\n\n if (caseSensitive) {\n query += ` case:yes`;\n } else {\n query += ` case:no`;\n }\n\n console.error(`Executing search request: ${query}`);\n\n const response = await search({\n query,\n matches: env.DEFAULT_MATCHES,\n contextLines: env.DEFAULT_CONTEXT_LINES,\n });\n\n if (isServiceError(response)) {\n return {\n content: [{\n type: \"text\",\n text: `Error searching code: ${response.message}`,\n }],\n };\n }\n\n if (response.files.length === 0) {\n return {\n content: [{\n type: \"text\",\n text: `No results found for the query: ${query}`,\n }],\n };\n }\n\n const content: TextContent[] = [];\n let totalTokens = 0;\n let isResponseTruncated = false;\n\n for (const file of response.files) {\n const numMatches = file.chunks.reduce(\n (acc, chunk) => acc + chunk.matchRanges.length,\n 0,\n );\n let text = `file: ${file.url}\\nnum_matches: ${numMatches}\\nrepository: ${file.repository}\\nlanguage: ${file.language}`;\n\n if (includeCodeSnippets) {\n const snippets = file.chunks.map(chunk => {\n const content = base64Decode(chunk.content);\n return `\\`\\`\\`\\n${content}\\n\\`\\`\\``\n }).join('\\n');\n text += `\\n\\n${snippets}`;\n }\n\n\n // Rough estimate of the number of tokens in the text\n // @see: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them\n const tokens = text.length / 4;\n\n if ((totalTokens + tokens) > maxTokens) {\n isResponseTruncated = true;\n break;\n }\n\n totalTokens += tokens;\n content.push({\n type: \"text\",\n text,\n });\n }\n\n if (isResponseTruncated) {\n content.push({\n type: \"text\",\n text: `The response was truncated because the number of tokens exceeded the maximum limit of ${maxTokens}.`,\n });\n }\n\n return {\n content,\n }\n }\n);\n\nserver.tool(\n \"list_repos\",\n \"Lists all repositories in the organization.\",\n async () => {\n const response = await listRepos();\n if (isServiceError(response)) {\n return {\n content: [{\n type: \"text\",\n text: `Error listing repositories: ${response.message}`,\n }],\n };\n }\n\n const content: TextContent[] = response.repos.map(repo => {\n return {\n type: \"text\",\n text: `id: ${repo.name}\\nurl: ${repo.url}`,\n }\n });\n\n return {\n content,\n };\n }\n);\n\nserver.tool(\n \"get_file_source\",\n \"Fetches the source code for a given file.\",\n {\n fileName: z.string().describe(\"The file to fetch the source code for.\"),\n repository: z.string().describe(\"The repository to fetch the source code for. This is the Sourcebot compatible repository ID.\"),\n },\n async ({ fileName, repository }) => {\n const response = await getFileSource({\n fileName,\n repository,\n });\n\n if (isServiceError(response)) {\n return {\n content: [{\n type: \"text\",\n text: `Error fetching file source: ${response.message}`,\n }],\n };\n }\n\n const content: TextContent[] = [{\n type: \"text\",\n text: `file: ${fileName}\\nrepository: ${repository}\\nlanguage: ${response.language}\\nsource:\\n${base64Decode(response.source)}`,\n }]\n\n return {\n content,\n };\n }\n);\n\n\n\nconst runServer = async () => {\n const transport = new StdioServerTransport();\n await server.connect(transport);\n console.error('Sourcebot MCP server ready');\n}\n\nrunServer().catch((error) => {\n console.error('Failed to start MCP server:', error);\n process.exit(1);\n});\n"]}