Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 | import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { z } from 'zod'; import { ResultSchema, ErrorCode, McpError, SetLevelRequestSchema, ListResourcesRequestSchema, ListResourceTemplatesRequestSchema, ReadResourceRequestSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ResourceSchema, ResourceTemplateSchema, type Request, type Notification, type Result, type Tool, } from '@modelcontextprotocol/sdk/types.js'; import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js'; import { Connections, type Backend } from './connections'; import { connectionPanel, CONNECTION_PANEL_META, CONNECTION_PANEL_URI, CONNECTION_PANEL_NAMESPACE, } from './panel'; import { MCP_APPS_EXTENSION } from '../mcp-apps'; const PREFIX = 'gitlab_plugin_'; const { protocol: LOCAL_RESOURCE_PROTOCOL, host: LOCAL_RESOURCE_AUTHORITY } = new URL( CONNECTION_PANEL_NAMESPACE, ); const LOCAL_RESOURCE_SCHEME = LOCAL_RESOURCE_PROTOCOL + '//'; // https://modelcontextprotocol.io/specification/2025-11-25/server/resources#error-handling const RESOURCE_NOT_FOUND = -32002; // Preserve provider extension fields while validating the resources merged into our catalog. const ResourceCatalogSchema = ListResourcesResultSchema.extend({ resources: z.array(ResourceSchema.loose()), }); const ResourceTemplateCatalogSchema = ListResourceTemplatesResultSchema.extend({ resourceTemplates: z.array(ResourceTemplateSchema.loose()), }); const EMPTY_INPUT = { type: 'object' as const, properties: {}, additionalProperties: false }; const OBJECT_OUTPUT = { type: 'object' as const, additionalProperties: true }; const ConnectionAction = z.object({ action: z.enum(['status', 'connect', 'reconnect', 'cancel', 'disconnect']), revision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), connection: z.unknown().optional(), }); const tools: Tool[] = [ { name: PREFIX + 'open_connection', description: 'Open private GitLab connection setup. Choose local GitLab or an existing MCP server.', inputSchema: EMPTY_INPUT, _meta: { ui: { resourceUri: CONNECTION_PANEL_URI } }, }, { name: PREFIX + 'connection', description: 'Manage this plugin connection from the private setup panel.', inputSchema: { type: 'object', properties: { action: { enum: [...ConnectionAction.shape.action.options] }, revision: { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER }, connection: { type: 'object' }, }, required: ['action', 'revision'], additionalProperties: false, }, outputSchema: OBJECT_OUTPUT, _meta: { ui: { visibility: ['app'] } }, }, { name: PREFIX + 'get_settings', description: 'Read plugin connection and backend account settings.', inputSchema: EMPTY_INPUT, outputSchema: OBJECT_OUTPUT, }, { name: PREFIX + 'update_settings', description: 'Update backend account settings.', inputSchema: { type: 'object', properties: { set: { type: 'object' } }, required: ['set'] }, outputSchema: OBJECT_OUTPUT, }, ]; const result = (value: Record<string, unknown>): Result => ({ content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value, }); function resourceRequest<T extends Request>(schema: z.ZodType<T>, request: Request): T { const parsed = schema.safeParse(request); if (!parsed.success) throw new McpError(ErrorCode.InvalidParams, 'Invalid resource request parameters.'); return parsed.data; } function localResourcePathOffset(uri: string): number | null { // https://www.rfc-editor.org/rfc/rfc3986#section-6.2.2.2 // Normalize authority aliases without rewriting the path or reserved delimiters. if (uri.slice(0, LOCAL_RESOURCE_SCHEME.length).toLowerCase() !== LOCAL_RESOURCE_SCHEME) return null; // Each ASCII authority character expands to at most three URI characters. const prefix = uri.slice( LOCAL_RESOURCE_SCHEME.length, LOCAL_RESOURCE_SCHEME.length + LOCAL_RESOURCE_AUTHORITY.length * 3 + 1, ); const end = prefix.indexOf('/'); if (end < 0) return null; try { const authority = decodeURI(prefix.slice(0, end)).toLowerCase(); return authority === LOCAL_RESOURCE_AUTHORITY ? LOCAL_RESOURCE_SCHEME.length + end + 1 : null; } catch { // Malformed percent encoding cannot identify the local authority. return null; } } function hasLocalResourceContent(response: Result): boolean { return ( Array.isArray(response.contents) && response.contents.some( (content: unknown) => typeof content === 'object' && content !== null && 'uri' in content && typeof content.uri === 'string' && localResourcePathOffset(content.uri) !== null, ) ); } async function readResource( request: z.infer<typeof ReadResourceRequestSchema>, extra: RequestHandlerExtra<Request, Notification>, connections: Connections, ): Promise<Result> { const uri = request.params.uri; const localPathOffset = localResourcePathOffset(uri); if ( localPathOffset !== null && uri.slice(localPathOffset) === CONNECTION_PANEL_URI.slice(CONNECTION_PANEL_NAMESPACE.length) ) return { contents: [ { uri, mimeType: 'text/html;profile=mcp-app', text: connectionPanel(), _meta: CONNECTION_PANEL_META, }, ], }; if (localPathOffset === null) { const backend = await connections.ready(); if (backend?.client.getServerCapabilities()?.resources) { const response = await forward(backend, request, extra, connections, ResultSchema); if (hasLocalResourceContent(response)) throw new McpError( ErrorCode.InvalidRequest, 'Backend read result uses reserved plugin resource URIs.', ); return response; } } throw new McpError(RESOURCE_NOT_FOUND, 'Resource not found', { uri }); } async function resourceTemplates( request: Request, extra: RequestHandlerExtra<Request, Notification>, connections: Connections, ): Promise<Result> { const backend = await connections.ready(); if (!backend?.client.getServerCapabilities()?.resources) return { resourceTemplates: [] }; try { const response = await forward( backend, request, extra, connections, ResourceTemplateCatalogSchema, ); // Broad templates remain available; concrete local URI ownership is enforced on reads. // Only an explicit local namespace declaration conflicts with this catalog. if ( (response.resourceTemplates as z.infer<typeof ResourceTemplateSchema>[]).some( (template) => localResourcePathOffset(template.uriTemplate) !== null, ) ) throw new McpError( ErrorCode.InvalidRequest, 'Backend uses reserved plugin resource templates.', ); return response; } catch (error) { if (!(error instanceof McpError) || error.code !== ErrorCode.MethodNotFound) throw error; // Static-resource servers may omit templates; this is not an authorization failure. assertCurrentBackend(backend, connections); return { resourceTemplates: [] }; } } /** Public MCP bridge; GitLab behavior and account authority stay at the selected backend. */ export function createPluginServer( connections: Connections, ): Server<Request, Notification, Result> { const server = new Server<Request, Notification, Result>( { name: 'gitlab-mcp-plugin', version: '1.0.0' }, { capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, extensions: MCP_APPS_EXTENSION, prompts: { listChanged: true }, logging: {}, experimental: { 'openai/settings': { readTool: PREFIX + 'get_settings', updateTool: PREFIX + 'update_settings', }, }, }, instructions: 'Use gitlab_plugin_open_connection to configure or reconnect GitLab. Credentials belong only in the private connection panel, never in chat. GitLab tools appear after connecting.', }, ); connections.changed = () => { void server.notification({ method: 'notifications/tools/list_changed' }).catch(() => {}); void server.notification({ method: 'notifications/resources/list_changed' }).catch(() => {}); void server.notification({ method: 'notifications/prompts/list_changed' }).catch(() => {}); }; connections.wire = (backend) => { backend.client.fallbackRequestHandler = (request, extra) => { if (connections.active !== backend) throw new McpError(ErrorCode.InvalidRequest, 'The connection is no longer active.'); return server.request(request, ResultSchema, { signal: extra.signal }); }; backend.client.fallbackNotificationHandler = async (notification) => { if (connections.active === backend) await server.notification(notification); }; }; server.oninitialized = () => { connections.capabilities = server.getClientCapabilities() ?? {}; }; server.setRequestHandler(SetLevelRequestSchema, async (request, extra) => { const backend = await connections.ready(); return backend?.client.getServerCapabilities()?.logging ? forward(backend, request, extra, connections, ResultSchema) : {}; }); server.fallbackNotificationHandler = async (notification) => { const backend = await connections.ready(); if (backend) await backend.client.notification(notification); }; server.fallbackRequestHandler = async (request, extra) => { if (request.method === 'resources/subscribe' || request.method === 'resources/unsubscribe') throw new McpError(ErrorCode.MethodNotFound, 'Resource subscriptions are not supported.'); if (request.method === 'resources/read') return readResource(resourceRequest(ReadResourceRequestSchema, request), extra, connections); if (request.method === 'resources/list') { const validated = resourceRequest(ListResourcesRequestSchema, request); return resourceListing(await connections.ready(), validated, extra, connections); } if (request.method === 'resources/templates/list') return resourceTemplates( resourceRequest(ListResourceTemplatesRequestSchema, request), extra, connections, ); const params = request.params ?? {}; if ( request.method === 'tools/call' && typeof params.name === 'string' && params.name.startsWith(PREFIX) ) { return localTool(params.name, params.arguments, connections, extra); } const backend = await connections.ready(); if (request.method === 'tools/list') return toolListing(backend, request, extra, connections); if (request.method === 'prompts/list' && !backend?.client.getServerCapabilities()?.prompts) return { prompts: [] }; if (!backend) throw new McpError( ErrorCode.InvalidRequest, 'Open GitLab connection settings to connect or reconnect.', ); return forward(backend, request, extra, connections, ResultSchema); }; return server; } async function toolListing( backend: Backend | undefined, request: Request, extra: RequestHandlerExtra<Request, Notification>, connections: Connections, ): Promise<Result> { const response = backend ? await forward(backend, request, extra, connections, ResultSchema) : { tools: [] }; const offered = response.tools as Tool[]; if (offered.some((tool) => tool.name.startsWith(PREFIX))) throw new McpError(ErrorCode.InvalidRequest, 'Backend uses reserved plugin tool names.'); return { ...response, tools: request.params?.cursor !== undefined ? offered : [...tools, ...offered], }; } async function resourceListing( backend: Backend | undefined, request: Request, extra: RequestHandlerExtra<Request, Notification>, connections: Connections, ): Promise<Result> { const response = backend?.client.getServerCapabilities()?.resources ? await forward(backend, request, extra, connections, ResourceCatalogSchema) : { resources: [] }; // The local UI authority belongs to this plugin, never to a connected provider. if ( (response.resources as z.infer<typeof ResourceSchema>[]).some( (resource) => localResourcePathOffset(resource.uri) !== null, ) ) throw new McpError(ErrorCode.InvalidRequest, 'Backend uses reserved plugin resource URIs.'); return { ...response, resources: request.params?.cursor !== undefined ? response.resources : [ { uri: CONNECTION_PANEL_URI, name: 'GitLab connection', mimeType: 'text/html;profile=mcp-app', _meta: CONNECTION_PANEL_META, }, ...(response.resources as unknown[]), ], }; } async function forward( backend: Backend, request: Request, extra: RequestHandlerExtra<Request, Notification>, connections: Connections, schema: typeof ResultSchema | typeof ResourceCatalogSchema | typeof ResourceTemplateCatalogSchema, ): Promise<Result> { const token = request.params?._meta?.progressToken; const response = await backend.client .request(request, schema, { signal: extra.signal, ...(token !== undefined ? { onprogress: (progress) => { void extra .sendNotification({ method: 'notifications/progress', params: { ...progress, progressToken: token }, }) .catch(() => {}); }, } : {}), }) .catch((error: unknown) => { // JSON-RPC errors belong to the backend contract. Transport errors can quote HTTP bodies or credentials. if (error instanceof McpError) throw error; throw new McpError( ErrorCode.InternalError, 'The connection request failed. Its outcome may be unknown. Check connection settings before retrying; do not repeat writes automatically.', ); }); assertCurrentBackend(backend, connections); return response; } function assertCurrentBackend(backend: Backend, connections: Connections): void { if ( connections.active !== backend || connections.store.revision() !== backend.snapshot.revision ) { throw new McpError( ErrorCode.InvalidRequest, 'Connection changed while this request was running. Its outcome may be unknown. Do not repeat writes automatically.', ); } } async function connectionAction(raw: unknown, connections: Connections): Promise<Result> { const parsed = ConnectionAction.safeParse(raw); if (!parsed.success) { const revision = parsed.error.issues.some( (issue) => issue.path.length === 0 || issue.path[0] === 'revision', ); throw new McpError( ErrorCode.InvalidParams, revision ? 'Invalid connection revision.' : 'Unknown connection action.', ); } const args = parsed.data; switch (args.action) { case 'status': await connections.ready(); break; case 'connect': return result(await connections.connect(args.connection, args.revision)); case 'reconnect': { const saved = connections.store.read(); if (!saved.connection) throw new McpError(ErrorCode.InvalidParams, 'Configure a connection first.'); const { authorization: _authorization, ...input } = saved.connection; return result(await connections.connect(input, args.revision)); } case 'disconnect': await connections.disconnect(args.revision); break; case 'cancel': await connections.cancel(); break; } return result(connections.status()); } async function connectionSettings( backend: Backend | undefined, connections: Connections, extra: RequestHandlerExtra<Request, Notification>, ): Promise<Result> { let unavailable = false; let page: Record<string, unknown> = { schema: { type: 'object', properties: {}, required: [] }, values: {}, layout: [], }; if (backend) { try { const response = await forward( backend, { method: 'tools/call', params: { name: 'get_settings', arguments: {} } }, extra, connections, ResultSchema, ); if (response.isError) unavailable = true; else if (response.structuredContent) page = response.structuredContent as Record<string, unknown>; } catch { // Local reconnection controls remain available when backend settings cannot be read. unavailable = true; } } return result({ ...page, layout: [ { kind: 'group', title: 'Connection', items: [ { kind: 'tool', tool: PREFIX + 'open_connection', description: unavailable ? 'Backend account settings are unavailable. Set up, change or reconnect GitLab.' : 'Set up, change or reconnect GitLab', }, ], }, ...(page.layout as unknown[]), ], }); } async function localTool( name: string, raw: unknown, connections: Connections, extra: RequestHandlerExtra<Request, Notification>, ): Promise<Result> { if (name === PREFIX + 'open_connection') return { content: [{ type: 'text', text: 'Configure your connection in the private panel.' }], _meta: { ui: { resourceUri: CONNECTION_PANEL_URI } }, }; if (name === PREFIX + 'connection') return connectionAction(raw, connections); const backend = await connections.ready(); if (name === PREFIX + 'get_settings') return connectionSettings(backend, connections, extra); if (name === PREFIX + 'update_settings' && backend) return forward( backend, { method: 'tools/call', params: { name: 'update_settings', arguments: raw as Record<string, unknown> }, }, extra, connections, ResultSchema, ); throw new McpError(ErrorCode.InvalidRequest, 'Connect GitLab before changing account settings.'); } |