@gtkx/mcp 1.6.0 → 2.0.0-beta.2
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 +5 -5
- package/dist/app-router.d.ts +6 -2
- package/dist/app-router.d.ts.map +1 -1
- package/dist/app-router.js +56 -19
- package/dist/app-router.js.map +1 -1
- package/dist/internal.d.ts +2 -1
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +2 -1
- package/dist/internal.js.map +1 -1
- package/dist/protocol/schemas.d.ts +1 -2
- package/dist/protocol/schemas.d.ts.map +1 -1
- package/dist/protocol/schemas.js +1 -7
- package/dist/protocol/schemas.js.map +1 -1
- package/dist/reference.d.ts.map +1 -1
- package/dist/reference.js +13 -35
- package/dist/reference.js.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +86 -39
- package/dist/server.js.map +1 -1
- package/dist/socket-path.d.ts +11 -0
- package/dist/socket-path.d.ts.map +1 -0
- package/dist/socket-path.js +74 -0
- package/dist/socket-path.js.map +1 -0
- package/dist/socket-server.d.ts +3 -1
- package/dist/socket-server.d.ts.map +1 -1
- package/dist/socket-server.js +48 -32
- package/dist/socket-server.js.map +1 -1
- package/package.json +12 -8
- package/src/app-router.ts +77 -22
- package/src/internal.ts +4 -1
- package/src/protocol/schemas.ts +0 -9
- package/src/reference.ts +15 -42
- package/src/server.ts +107 -41
- package/src/socket-path.ts +103 -0
- package/src/socket-server.ts +61 -37
package/dist/reference.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reference.js","sourceRoot":"","sources":["../src/reference.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqC,gBAAgB,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtH,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAkB,gBAAgB,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EAAE,aAAa,CAAC,OAAO,EAAE,SAAS,EAAE,SAAS,CAAC,EAAE,KAAK,CAAC;SACpF;KACJ,CAAC,EACF;QACI,KAAK,EAAE,uBAAuB;QAC9B,WAAW,EACP,6FAA6F;YAC7F,yEAAyE;QAC7E,QAAQ,EAAE,eAAe;KAC5B,EACD,CAAC,GAAG,EAAE,SAAS,EAAE,EAAE,CACf,UAAU,CAAC,GAAG,EAAE,QAAQ,EAAE,aAAa,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,aAAa,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CACrG,CAAC;AACN,CAAC,CAAC;AAEF,MAAM,0BAA0B,GAAG,CAAC,MAAsB,EAAE,QAA2B,EAAQ,EAAE;IAC7F,qBAAqB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACxC,yBAAyB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAC5C,sBAAsB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AAC7C,CAAC,CAAC;AAEF,OAAO,EACH,uBAAuB,EACvB,mBAAmB,EACnB,0BAA0B,GAE7B,CAAC","sourcesContent":["import { type ApiReference, type ApiSymbol, loadApiReference, resolveGirPath, resolveLibraries } from \"@gtkx/codegen\";\nimport { loadConfig } from \"@gtkx/config\";\nimport { resolveFuture } from \"@gtkx/config/internal\";\nimport { type McpServer, ResourceTemplate } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { type CallToolResult, ErrorCode, McpError, type ReadResourceResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { existsSync, statSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { defineTool, textContent, textError, type Tool, type ToolArgs } from \"./tool.js\";\n\ntype ReferenceApi = Pick<\n ApiReference,\n \"lookup\" | \"namespaceOverview\" | \"namespaces\" | \"overview\" | \"search\" | \"symbolNames\"\n>;\n\ntype ProjectSource = \"argument\" | \"workingDirectory\" | \"app\";\n\ntype ResolvedProject = {\n root: string;\n source: ProjectSource;\n};\n\ntype ScopedReference = ResolvedProject & {\n reference: ReferenceApi;\n};\n\ntype ReferenceProviderOptions = {\n getAppRoot: () => string | undefined;\n getWorkingDirectory?: () => string;\n};\n\ntype ReferenceProvider = {\n get(projectRoot?: string): Promise<ScopedReference>;\n load(project: ResolvedProject): Promise<ScopedReference>;\n resolve(projectRoot?: string): ResolvedProject;\n};\n\ntype WatchedFile = {\n path: string;\n mtimeMs: number;\n size: number;\n};\n\ntype LoadedReference = {\n reference: ApiReference;\n root: string;\n watched: WatchedFile[];\n};\n\ntype CacheEntry = {\n pending: Promise<LoadedReference>;\n verifiedAt: number;\n failedAt: number | undefined;\n};\n\ntype ReferenceCache = Map<string, CacheEntry>;\ntype SearchOptions = Parameters<ReferenceApi[\"search\"]>[0];\ntype ResourceServer = Pick<McpServer, \"registerResource\">;\n\nconst FRESHNESS_INTERVAL_MS = 2000;\nconst FAILURE_RETRY_MS = 5000;\nconst CONFIG_EXTENSIONS = [\"ts\", \"mts\", \"cts\", \"js\", \"mjs\", \"cjs\", \"json\"];\n\nconst PROJECT_SOURCE_LABELS: Record<ProjectSource, string> = {\n argument: \"requested with `projectRoot`\",\n workingDirectory: \"found from the working directory\",\n app: \"taken from a connected app; pass `projectRoot` to document another project\",\n};\n\nconst SYMBOL_KIND = z.enum([\n \"element\",\n \"class\",\n \"interface\",\n \"record\",\n \"enum\",\n \"callback\",\n \"alias\",\n \"function\",\n \"constant\",\n]);\n\nconst SYMBOL_DESCRIPTION =\n \"Qualified symbol name (`Gtk.Button`, `Gtk.Orientation`, `GLib.idleAdd`), JSX element name (`GtkButton`), \" +\n \"or bare symbol name when unambiguous (`Button`).\";\n\nconst PROJECT_ROOT_DESCRIPTION =\n \"Directory of the GTKX project whose bindings to document, absolute or relative to the working directory. \" +\n \"Any directory inside the project works; its `gtkx.config.ts` decides the documented libraries. Omit to use \" +\n \"the project containing the working directory, falling back to a connected app's project.\";\n\nconst projectRootShape = {\n projectRoot: z.string().optional().describe(PROJECT_ROOT_DESCRIPTION),\n};\n\nconst listApiShape = {\n ...projectRootShape,\n namespace: z\n .string()\n .optional()\n .describe(\"Namespace to list (e.g. `Gtk`, `Adw`, `Gio`). Omit for an overview of all namespaces.\"),\n};\n\nconst searchApiShape = {\n ...projectRootShape,\n query: z.string().describe(\"Case-insensitive substring of a symbol name, e.g. `headerbar` or `orientation`.\"),\n namespace: z.string().optional().describe(\"Restrict matches to one namespace (e.g. `Gtk`).\"),\n kind: SYMBOL_KIND.optional().describe(\"Restrict matches to one symbol kind.\"),\n limit: z.number().int().min(1).optional().describe(\"Maximum number of results (default: 20).\"),\n};\n\nconst apiDocsShape = {\n ...projectRootShape,\n symbol: z.string().describe(SYMBOL_DESCRIPTION),\n kind: SYMBOL_KIND.optional().describe(\"Disambiguate when several kinds share the symbol name.\"),\n};\n\nconst watchFile = (path: string): WatchedFile => {\n try {\n const stats = statSync(path);\n\n return { path, mtimeMs: stats.mtimeMs, size: stats.size };\n } catch {\n return { path, mtimeMs: -1, size: -1 };\n }\n};\n\nconst isFresh = (loaded: LoadedReference): boolean =>\n loaded.watched.every((file) => {\n const current = watchFile(file.path);\n\n return current.mtimeMs === file.mtimeMs && current.size === file.size;\n });\n\nconst hasConfigFile = (directory: string): boolean =>\n CONFIG_EXTENSIONS.some((extension) => existsSync(join(directory, `gtkx.config.${extension}`)));\n\nconst findProjectRoot = (start: string): string | undefined => {\n const current = resolve(start);\n const parent = dirname(current);\n\n if (hasConfigFile(current)) {\n return current;\n }\n\n return parent === current ? undefined : findProjectRoot(parent);\n};\n\nconst projectAt = (candidate: string, source: ProjectSource): ResolvedProject => ({\n root: findProjectRoot(candidate) ?? resolve(candidate),\n source,\n});\n\nconst resolveProject = (\n workingDirectory: string,\n getAppRoot: () => string | undefined,\n projectRoot: string | undefined,\n): ResolvedProject => {\n if (projectRoot !== undefined) {\n return projectAt(projectRoot, \"argument\");\n }\n\n const discovered = findProjectRoot(workingDirectory);\n\n if (discovered !== undefined) {\n return { root: discovered, source: \"workingDirectory\" };\n }\n\n const appRoot = getAppRoot();\n\n return appRoot === undefined\n ? { root: resolve(workingDirectory), source: \"workingDirectory\" }\n : projectAt(appRoot, \"app\");\n};\n\nconst loadReference = async (requestedRoot: string): Promise<LoadedReference> => {\n const { config, configFile, root } = await loadConfig(requestedRoot);\n\n if (config.codegen === false) {\n throw new Error(\n `codegen is disabled for the project at ${root}, so there are no generated bindings to document. ` +\n \"Remove `codegen: false` from gtkx.config.ts to use the API reference, or point the `projectRoot` \" +\n \"argument at another project.\",\n );\n }\n\n const girPath = resolveGirPath(config.girPath);\n\n if (girPath.length === 0) {\n throw new Error(\n \"No GIR search paths available. Install gobject-introspection \" +\n \"(Linux: `sudo dnf install gobject-introspection-devel` or `sudo apt install libgirepository1.0-dev`), \" +\n \"or set `girPath` in gtkx.config.ts.\",\n );\n }\n\n const future = resolveFuture(config.future);\n const libraries = resolveLibraries(config.libraries, girPath, future.isAdwaitaDefault);\n\n const reference = loadApiReference({\n libraries,\n girPath,\n isByteArrayTyped: future.isByteArrayTyped,\n isValueUnwrapped: future.isValueUnwrapped,\n isFinishTrimmed: future.isFinishTrimmed,\n isInoutInPlace: future.isInoutInPlace,\n isTreeShaken: future.isTreeShaken,\n });\n\n const watched = [watchFile(resolve(root, configFile)), ...reference.girFiles.map((file) => watchFile(file))];\n\n return { reference, root, watched };\n};\n\nconst markFailed = async (entry: CacheEntry): Promise<void> => {\n try {\n await entry.pending;\n } catch {\n entry.failedAt = Date.now();\n }\n};\n\nconst startLoad = (cache: ReferenceCache, root: string): CacheEntry => {\n const entry: CacheEntry = { pending: loadReference(root), verifiedAt: Date.now(), failedAt: undefined };\n void markFailed(entry);\n cache.set(root, entry);\n\n return entry;\n};\n\nconst isRetryDue = (entry: CacheEntry): boolean =>\n entry.failedAt !== undefined && Date.now() - entry.failedAt >= FAILURE_RETRY_MS;\n\nconst resolveEntry = (cache: ReferenceCache, root: string): CacheEntry => {\n const entry = cache.get(root) ?? startLoad(cache, root);\n\n return isRetryDue(entry) ? startLoad(cache, root) : entry;\n};\n\nconst revalidate = (cache: ReferenceCache, root: string, entry: CacheEntry): CacheEntry => {\n const current = cache.get(root);\n\n return current === undefined || current === entry ? startLoad(cache, root) : current;\n};\n\nconst currentReference = async (cache: ReferenceCache, root: string): Promise<LoadedReference> => {\n const entry = resolveEntry(cache, root);\n const loaded = await entry.pending;\n\n if (Date.now() - entry.verifiedAt < FRESHNESS_INTERVAL_MS) {\n return loaded;\n }\n\n if (isFresh(loaded)) {\n entry.verifiedAt = Date.now();\n\n return loaded;\n }\n\n return revalidate(cache, root, entry).pending;\n};\n\nconst defaultWorkingDirectory = (): string => process.cwd();\n\nconst createReferenceProvider = (options: ReferenceProviderOptions): ReferenceProvider => {\n const cache: ReferenceCache = new Map();\n const getWorkingDirectory = options.getWorkingDirectory ?? defaultWorkingDirectory;\n\n const resolve = (projectRoot?: string): ResolvedProject =>\n resolveProject(getWorkingDirectory(), options.getAppRoot, projectRoot);\n\n const load = async (project: ResolvedProject): Promise<ScopedReference> => {\n const loaded = await currentReference(cache, project.root);\n\n return { reference: loaded.reference, root: loaded.root, source: project.source };\n };\n\n const get = (projectRoot?: string): Promise<ScopedReference> => load(resolve(projectRoot));\n\n return { get, load, resolve };\n};\n\nconst projectNote = (project: ResolvedProject): string =>\n `Project: ${project.root} (${PROJECT_SOURCE_LABELS[project.source]})`;\n\nconst withProjectNote = (result: CallToolResult, note: string): CallToolResult => ({\n ...result,\n content: [...result.content, { type: \"text\", text: note }],\n});\n\nconst scopedResult = async (\n provider: ReferenceProvider,\n projectRoot: string | undefined,\n render: (reference: ReferenceApi) => CallToolResult,\n): Promise<CallToolResult> => {\n const resolved = provider.resolve(projectRoot);\n\n try {\n const scoped = await provider.load(resolved);\n\n return withProjectNote(render(scoped.reference), projectNote(scoped));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n\n return withProjectNote(textError(message), projectNote(resolved));\n }\n};\n\nconst formatCandidates = (candidates: ApiSymbol[]): string =>\n candidates.map((candidate) => `- ${candidate.namespace}.${candidate.name} (${candidate.kind})`).join(\"\\n\");\n\nconst buildSearchOptions = (args: ToolArgs<typeof searchApiShape>): SearchOptions => {\n const options: SearchOptions = { query: args.query };\n\n if (args.namespace !== undefined) {\n options.namespace = args.namespace;\n }\n\n if (args.kind !== undefined) {\n options.kinds = [args.kind];\n }\n\n if (args.limit !== undefined) {\n options.limit = args.limit;\n }\n\n return options;\n};\n\nconst listApiResult = (reference: ReferenceApi, namespace: string | undefined): CallToolResult => {\n if (namespace === undefined) {\n return textContent(reference.overview());\n }\n\n const overview = reference.namespaceOverview(namespace);\n\n if (overview === undefined) {\n const names = reference\n .namespaces()\n .map((summary) => summary.name)\n .join(\", \");\n\n return textError(`Unknown namespace \"${namespace}\". Available namespaces: ${names}`);\n }\n\n return textContent(overview);\n};\n\nconst searchApiResult = (reference: ReferenceApi, args: ToolArgs<typeof searchApiShape>): CallToolResult => {\n const results = reference.search(buildSearchOptions(args));\n\n if (results.length === 0) {\n return textContent(`No symbols matched \"${args.query}\". Try a shorter substring or \\`gtkx_list_api\\`.`);\n }\n\n return textContent(JSON.stringify(results, null, 2));\n};\n\nconst apiDocsResult = (reference: ReferenceApi, args: ToolArgs<typeof apiDocsShape>): CallToolResult => {\n const result = reference.lookup(args.symbol, args.kind);\n\n if (result.outcome === \"notFound\") {\n return textError(`No symbol named \"${args.symbol}\". Use \\`gtkx_search_api\\` to find the right name.`);\n }\n\n if (result.outcome === \"ambiguous\") {\n return textError(\n `\"${args.symbol}\" matches several symbols. Pass a qualified name or a kind:\\n` +\n formatCandidates(result.candidates),\n );\n }\n\n return textContent(result.markdown);\n};\n\nconst listApiTool = (provider: ReferenceProvider): Tool =>\n defineTool({\n name: \"gtkx_list_api\",\n title: \"List API reference\",\n kind: \"readOnly\",\n description:\n \"List the project's generated GTK4 bindings API (`@gtkx/gi` and `@gtkx/jsx`). Without a namespace, \" +\n \"returns every namespace with symbol counts; with a namespace, lists all of its symbols grouped by kind.\",\n inputSchema: listApiShape,\n handler: ({ namespace, projectRoot }) =>\n scopedResult(provider, projectRoot, (reference) => listApiResult(reference, namespace)),\n });\n\nconst searchApiTool = (provider: ReferenceProvider): Tool =>\n defineTool({\n name: \"gtkx_search_api\",\n title: \"Search API reference\",\n kind: \"readOnly\",\n description:\n \"Search the project's generated GTK4 bindings API by symbol name. Returns matching symbols with \" +\n \"their namespace, kind, and a one-line summary; fetch full pages with `gtkx_get_api_docs`.\",\n inputSchema: searchApiShape,\n handler: (args) => scopedResult(provider, args.projectRoot, (reference) => searchApiResult(reference, args)),\n });\n\nconst getApiDocsTool = (provider: ReferenceProvider): Tool =>\n defineTool({\n name: \"gtkx_get_api_docs\",\n title: \"Get API docs\",\n kind: \"readOnly\",\n description:\n \"Get the full reference page for one symbol of the project's generated GTK4 bindings: JSX elements \" +\n \"(props, signals, methods) or `@gtkx/gi` classes, interfaces, records, enums, callbacks, aliases, \" +\n \"functions, and constants.\",\n inputSchema: apiDocsShape,\n handler: (args) => scopedResult(provider, args.projectRoot, (reference) => apiDocsResult(reference, args)),\n });\n\nconst buildReferenceTools = (provider: ReferenceProvider): Tool[] => [\n listApiTool(provider),\n searchApiTool(provider),\n getApiDocsTool(provider),\n];\n\nconst markdownResource = (uri: URL, text: string): ReadResourceResult => ({\n contents: [{ uri: uri.href, mimeType: \"text/markdown\", text }],\n});\n\nconst variableValue = (value: string | string[] | undefined): string =>\n Array.isArray(value) ? (value[0] ?? \"\") : (value ?? \"\");\n\nconst withLoadFallback = async <T>(load: () => Promise<T>, fallback: T): Promise<T> => {\n try {\n return await load();\n } catch {\n return fallback;\n }\n};\n\nconst namesStartingWith = (names: string[], value: string): string[] =>\n names.filter((name) => name.toLowerCase().startsWith(value.toLowerCase()));\n\nconst completeNames = (\n provider: ReferenceProvider,\n value: string,\n collect: (reference: ReferenceApi) => string[],\n): Promise<string[]> =>\n withLoadFallback(async () => {\n const { reference } = await provider.get();\n\n return namesStartingWith(collect(reference), value);\n }, []);\n\nconst namespaceCompleter =\n (provider: ReferenceProvider) =>\n (value: string): Promise<string[]> =>\n completeNames(provider, value, (reference) => reference.namespaces().map((summary) => summary.name));\n\nconst completeSymbol = (provider: ReferenceProvider, namespace: string, value: string): Promise<string[]> => {\n if (namespace.length === 0) {\n return Promise.resolve([]);\n }\n\n return completeNames(provider, value, (reference) => reference.symbolNames(namespace));\n};\n\nconst resourceNotFound = (message: string): McpError => new McpError(ErrorCode.InvalidParams, message);\n\nconst symbolPage = async (\n uri: URL,\n provider: ReferenceProvider,\n namespace: string,\n symbol: string,\n): Promise<ReadResourceResult> => {\n const { reference } = await provider.get();\n const result = reference.lookup(`${namespace}.${symbol}`);\n\n if (result.outcome === \"page\") {\n return markdownResource(uri, result.markdown);\n }\n\n if (result.outcome === \"ambiguous\") {\n throw resourceNotFound(\n `\"${namespace}.${symbol}\" matches several symbols:\\n${formatCandidates(result.candidates)}`,\n );\n }\n\n throw resourceNotFound(`No symbol named \"${namespace}.${symbol}\"`);\n};\n\nconst registerIndexResource = (server: ResourceServer, provider: ReferenceProvider): void => {\n server.registerResource(\n \"gtkx-api-reference\",\n \"gtkx://reference/index\",\n {\n title: \"GTKX API reference index\",\n description: \"Namespaces of the project's generated GTK4 bindings, with symbol and JSX element counts.\",\n mimeType: \"text/markdown\",\n },\n async (uri) => {\n const { reference } = await provider.get();\n\n return markdownResource(uri, reference.overview());\n },\n );\n};\n\nconst registerNamespaceResource = (server: ResourceServer, provider: ReferenceProvider): void => {\n server.registerResource(\n \"gtkx-api-namespace\",\n new ResourceTemplate(\"gtkx://reference/{namespace}\", {\n list: () =>\n withLoadFallback(\n async () => {\n const { reference } = await provider.get();\n\n return {\n resources: reference.namespaces().map((summary) => ({\n uri: `gtkx://reference/${summary.name}`,\n name: `${summary.name} namespace reference`,\n mimeType: \"text/markdown\",\n })),\n };\n },\n { resources: [] },\n ),\n complete: {\n namespace: namespaceCompleter(provider),\n },\n }),\n {\n title: \"GTKX namespace reference\",\n description: \"All symbols of one namespace of the project's generated GTK4 bindings, grouped by kind.\",\n mimeType: \"text/markdown\",\n },\n async (uri, variables) => {\n const namespace = variableValue(variables.namespace);\n const { reference } = await provider.get();\n const overview = reference.namespaceOverview(namespace);\n\n if (overview === undefined) {\n throw resourceNotFound(`Unknown namespace \"${namespace}\"`);\n }\n\n return markdownResource(uri, overview);\n },\n );\n};\n\nconst registerSymbolResource = (server: ResourceServer, provider: ReferenceProvider): void => {\n server.registerResource(\n \"gtkx-api-symbol\",\n new ResourceTemplate(\"gtkx://reference/{namespace}/{symbol}\", {\n list: undefined,\n complete: {\n namespace: namespaceCompleter(provider),\n symbol: (value, context) =>\n completeSymbol(provider, variableValue(context?.arguments?.namespace), value),\n },\n }),\n {\n title: \"GTKX symbol reference\",\n description:\n \"Reference page for one symbol of the project's generated GTK4 bindings: a JSX element or a \" +\n \"class, interface, record, enum, callback, alias, function, or constant.\",\n mimeType: \"text/markdown\",\n },\n (uri, variables) =>\n symbolPage(uri, provider, variableValue(variables.namespace), variableValue(variables.symbol)),\n );\n};\n\nconst registerReferenceResources = (server: ResourceServer, provider: ReferenceProvider): void => {\n registerIndexResource(server, provider);\n registerNamespaceResource(server, provider);\n registerSymbolResource(server, provider);\n};\n\nexport {\n createReferenceProvider,\n buildReferenceTools,\n registerReferenceResources,\n type ReferenceProvider,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"reference.js","sourceRoot":"","sources":["../src/reference.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqC,gBAAgB,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtH,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAkB,gBAAgB,EAAE,MAAM,yCAAyC,CAAC;AAC3F,OAAO,EAAuB,SAAS,EAAE,QAAQ,EAA2B,MAAM,oCAAoC,CAAC;AACvH,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;A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AE,QAAQ,CAAC,CAAC;IAC3C,CAAC,CACJ,CAAC;AACN,CAAC,CAAC;AAEF,MAAM,sBAAsB,GAAG,CAAC,MAAsB,EAAE,QAA2B,EAAQ,EAAE;IACzF,MAAM,CAAC,gBAAgB,CACnB,iBAAiB,EACjB,IAAI,gBAAgB,CAAC,uCAAuC,EAAE;QAC1D,IAAI,EAAE,SAAS;QACf,QAAQ,EAAE;YACN,SAAS,EAAE,kBAAkB,CAAC,QAAQ,CAAC;YACvC,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,CACvB,cAAc,CAAC,QAAQ,EAAE,aAAa,CAAC,OAAO,EAAE,SAAS,EAAE,SAAS,CAAC,EAAE,KAAK,CAAC;SACpF;KACJ,CAAC,EACF;QACI,KAAK,EAAE,uBAAuB;QAC9B,WAAW,EACP,6FAA6F;YAC7F,yEAAyE;QAC7E,QAAQ,EAAE,eAAe;KAC5B,EACD,CAAC,GAAG,EAAE,SAAS,EAAE,EAAE,CACf,UAAU,CAAC,GAAG,EAAE,QAAQ,EAAE,aAAa,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,aAAa,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CACrG,CAAC;AACN,CAAC,CAAC;AAEF,MAAM,0BAA0B,GAAG,CAAC,MAAsB,EAAE,QAA2B,EAAQ,EAAE;IAC7F,qBAAqB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACxC,yBAAyB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAC5C,sBAAsB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AAC7C,CAAC,CAAC;AAEF,OAAO,EACH,uBAAuB,EACvB,mBAAmB,EACnB,0BAA0B,GAE7B,CAAC","sourcesContent":["import { type ApiReference, type ApiSymbol, loadApiReference, resolveGirPath, resolveLibraries } from \"@gtkx/codegen\";\nimport { loadConfig } from \"@gtkx/config\";\nimport { type McpServer, ResourceTemplate } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { type CallToolResult, ErrorCode, McpError, type ReadResourceResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { existsSync, statSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { defineTool, textContent, textError, type Tool, type ToolArgs } from \"./tool.js\";\n\ntype ReferenceApi = Pick<\n ApiReference,\n \"lookup\" | \"namespaceOverview\" | \"namespaces\" | \"overview\" | \"search\" | \"symbolNames\"\n>;\n\ntype ProjectSource = \"argument\" | \"workingDirectory\" | \"app\";\n\ntype ResolvedProject = {\n root: string;\n source: ProjectSource;\n};\n\ntype ScopedReference = ResolvedProject & {\n reference: ReferenceApi;\n};\n\ntype ReferenceProviderOptions = {\n getAppRoot: () => string | undefined;\n getWorkingDirectory?: () => string;\n};\n\ntype ReferenceProvider = {\n get(projectRoot?: string): Promise<ScopedReference>;\n load(project: ResolvedProject): Promise<ScopedReference>;\n resolve(projectRoot?: string): ResolvedProject;\n};\n\ntype WatchedFile = {\n path: string;\n mtimeMs: number;\n size: number;\n};\n\ntype LoadedReference = {\n reference: ApiReference;\n root: string;\n watched: WatchedFile[];\n};\n\ntype CacheEntry = {\n pending: Promise<LoadedReference>;\n verifiedAt: number;\n failedAt: number | undefined;\n};\n\ntype ReferenceCache = Map<string, CacheEntry>;\ntype SearchOptions = Parameters<ReferenceApi[\"search\"]>[0];\ntype ResourceServer = Pick<McpServer, \"registerResource\">;\n\nconst FRESHNESS_INTERVAL_MS = 2000;\nconst FAILURE_RETRY_MS = 5000;\nconst CONFIG_EXTENSIONS = [\"ts\", \"mts\", \"js\", \"mjs\", \"json\"];\n\nconst PROJECT_SOURCE_LABELS: Record<ProjectSource, string> = {\n argument: \"requested with `projectRoot`\",\n workingDirectory: \"found from the working directory\",\n app: \"taken from a connected app; pass `projectRoot` to document another project\",\n};\n\nconst SYMBOL_KIND = z.enum([\n \"element\",\n \"class\",\n \"interface\",\n \"record\",\n \"enum\",\n \"callback\",\n \"alias\",\n \"function\",\n \"constant\",\n]);\n\nconst SYMBOL_DESCRIPTION =\n \"Qualified symbol name (`Gtk.Button`, `Gtk.Orientation`, `GLib.idleAdd`), JSX element name (`GtkButton`), \" +\n \"or bare symbol name when unambiguous (`Button`).\";\n\nconst PROJECT_ROOT_DESCRIPTION =\n \"Directory of the GTKX project whose bindings to document, absolute or relative to the working directory. \" +\n \"Any directory inside the project works; its `gtkx.config.ts` decides the documented libraries. Omit to use \" +\n \"the project containing the working directory, falling back to a connected app's project.\";\n\nconst projectRootShape = {\n projectRoot: z.string().optional().describe(PROJECT_ROOT_DESCRIPTION),\n};\n\nconst listApiShape = {\n ...projectRootShape,\n namespace: z\n .string()\n .optional()\n .describe(\"Namespace to list (e.g. `Gtk`, `Adw`, `Gio`). Omit for an overview of all namespaces.\"),\n};\n\nconst searchApiShape = {\n ...projectRootShape,\n query: z.string().describe(\"Case-insensitive substring of a symbol name, e.g. `headerbar` or `orientation`.\"),\n namespace: z.string().optional().describe(\"Restrict matches to one namespace (e.g. `Gtk`).\"),\n kind: SYMBOL_KIND.optional().describe(\"Restrict matches to one symbol kind.\"),\n limit: z.number().int().min(1).optional().describe(\"Maximum number of results (default: 20).\"),\n};\n\nconst apiDocsShape = {\n ...projectRootShape,\n symbol: z.string().describe(SYMBOL_DESCRIPTION),\n kind: SYMBOL_KIND.optional().describe(\"Disambiguate when several kinds share the symbol name.\"),\n};\n\nconst watchFile = (path: string): WatchedFile => {\n try {\n const stats = statSync(path);\n\n return { path, mtimeMs: stats.mtimeMs, size: stats.size };\n } catch {\n return { path, mtimeMs: -1, size: -1 };\n }\n};\n\nconst isFresh = (loaded: LoadedReference): boolean =>\n loaded.watched.every((file) => {\n const current = watchFile(file.path);\n\n return current.mtimeMs === file.mtimeMs && current.size === file.size;\n });\n\nconst hasConfigFile = (directory: string): boolean =>\n CONFIG_EXTENSIONS.some((extension) => existsSync(join(directory, `gtkx.config.${extension}`)));\n\nconst findProjectRoot = (start: string): string | undefined => {\n const current = resolve(start);\n const parent = dirname(current);\n\n if (hasConfigFile(current)) {\n return current;\n }\n\n return parent === current ? undefined : findProjectRoot(parent);\n};\n\nconst projectAt = (candidate: string, source: ProjectSource): ResolvedProject => ({\n root: findProjectRoot(candidate) ?? resolve(candidate),\n source,\n});\n\nconst resolveProject = (\n workingDirectory: string,\n getAppRoot: () => string | undefined,\n projectRoot: string | undefined,\n): ResolvedProject => {\n if (projectRoot !== undefined) {\n return projectAt(projectRoot, \"argument\");\n }\n\n const discovered = findProjectRoot(workingDirectory);\n\n if (discovered !== undefined) {\n return { root: discovered, source: \"workingDirectory\" };\n }\n\n const appRoot = getAppRoot();\n\n return appRoot === undefined\n ? { root: resolve(workingDirectory), source: \"workingDirectory\" }\n : projectAt(appRoot, \"app\");\n};\n\nconst loadReference = async (requestedRoot: string): Promise<LoadedReference> => {\n const { config, configFile, root } = await loadConfig(requestedRoot);\n\n if (config.codegen === false) {\n throw new Error(\n `codegen is disabled for the project at ${root}, so there are no generated bindings to document. ` +\n \"Remove `codegen: false` from gtkx.config.ts to use the API reference, or point the `projectRoot` \" +\n \"argument at another project.\",\n );\n }\n\n const girPath = resolveGirPath(config.girPath);\n\n if (girPath.length === 0) {\n throw new Error(\n \"No GIR search paths available. Install gobject-introspection \" +\n \"(Linux: `sudo dnf install gobject-introspection-devel` or `sudo apt install libgirepository1.0-dev`), \" +\n \"or set `girPath` in gtkx.config.ts.\",\n );\n }\n\n const libraries = resolveLibraries(config.libraries);\n\n const reference = loadApiReference({\n libraries,\n girPath,\n });\n\n const watched = [watchFile(resolve(root, configFile)), ...reference.girFiles.map((file) => watchFile(file))];\n\n return { reference, root, watched };\n};\n\nconst startLoad = (cache: ReferenceCache, root: string): CacheEntry => {\n const entry: CacheEntry = { pending: loadReference(root), verifiedAt: Date.now(), failedAt: undefined };\n\n void entry.pending.catch(() => {\n entry.failedAt = Date.now();\n });\n\n cache.set(root, entry);\n\n return entry;\n};\n\nconst isRetryDue = (entry: CacheEntry): boolean =>\n entry.failedAt !== undefined && Date.now() - entry.failedAt >= FAILURE_RETRY_MS;\n\nconst resolveEntry = (cache: ReferenceCache, root: string): CacheEntry => {\n const entry = cache.get(root) ?? startLoad(cache, root);\n\n return isRetryDue(entry) ? startLoad(cache, root) : entry;\n};\n\nconst revalidate = (cache: ReferenceCache, root: string, entry: CacheEntry): CacheEntry => {\n const current = cache.get(root);\n\n return current === undefined || current === entry ? startLoad(cache, root) : current;\n};\n\nconst currentReference = async (cache: ReferenceCache, root: string): Promise<LoadedReference> => {\n const entry = resolveEntry(cache, root);\n const loaded = await entry.pending;\n\n if (Date.now() - entry.verifiedAt < FRESHNESS_INTERVAL_MS) {\n return loaded;\n }\n\n if (isFresh(loaded)) {\n entry.verifiedAt = Date.now();\n\n return loaded;\n }\n\n return revalidate(cache, root, entry).pending;\n};\n\nconst createReferenceProvider = (options: ReferenceProviderOptions): ReferenceProvider => {\n const cache: ReferenceCache = new Map();\n const getWorkingDirectory = options.getWorkingDirectory ?? (() => process.cwd());\n\n const resolve = (projectRoot?: string): ResolvedProject =>\n resolveProject(getWorkingDirectory(), options.getAppRoot, projectRoot);\n\n const load = async (project: ResolvedProject): Promise<ScopedReference> => {\n const loaded = await currentReference(cache, project.root);\n\n return { reference: loaded.reference, root: loaded.root, source: project.source };\n };\n\n const get = (projectRoot?: string): Promise<ScopedReference> => load(resolve(projectRoot));\n\n return { get, load, resolve };\n};\n\nconst projectNote = (project: ResolvedProject): string =>\n `Project: ${project.root} (${PROJECT_SOURCE_LABELS[project.source]})`;\n\nconst withProjectNote = (result: CallToolResult, note: string): CallToolResult => ({\n ...result,\n content: [...result.content, { type: \"text\", text: note }],\n});\n\nconst scopedResult = async (\n provider: ReferenceProvider,\n projectRoot: string | undefined,\n render: (reference: ReferenceApi) => CallToolResult,\n): Promise<CallToolResult> => {\n const resolved = provider.resolve(projectRoot);\n\n try {\n const scoped = await provider.load(resolved);\n\n return withProjectNote(render(scoped.reference), projectNote(scoped));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n\n return withProjectNote(textError(message), projectNote(resolved));\n }\n};\n\nconst formatCandidates = (candidates: ApiSymbol[]): string =>\n candidates.map((candidate) => `- ${candidate.namespace}.${candidate.name} (${candidate.kind})`).join(\"\\n\");\n\nconst buildSearchOptions = (args: ToolArgs<typeof searchApiShape>): SearchOptions => ({\n query: args.query,\n ...(args.namespace !== undefined && { namespace: args.namespace }),\n ...(args.kind !== undefined && { kinds: [args.kind] }),\n ...(args.limit !== undefined && { limit: args.limit }),\n});\n\nconst listApiResult = (reference: ReferenceApi, namespace: string | undefined): CallToolResult => {\n if (namespace === undefined) {\n return textContent(reference.overview());\n }\n\n const overview = reference.namespaceOverview(namespace);\n\n if (overview === undefined) {\n const names = reference\n .namespaces()\n .map((summary) => summary.name)\n .join(\", \");\n\n return textError(`Unknown namespace \"${namespace}\". Available namespaces: ${names}`);\n }\n\n return textContent(overview);\n};\n\nconst searchApiResult = (reference: ReferenceApi, args: ToolArgs<typeof searchApiShape>): CallToolResult => {\n const results = reference.search(buildSearchOptions(args));\n\n if (results.length === 0) {\n return textContent(`No symbols matched \"${args.query}\". Try a shorter substring or \\`gtkx_list_api\\`.`);\n }\n\n return textContent(JSON.stringify(results, null, 2));\n};\n\nconst apiDocsResult = (reference: ReferenceApi, args: ToolArgs<typeof apiDocsShape>): CallToolResult => {\n const result = reference.lookup(args.symbol, args.kind);\n\n if (result.outcome === \"notFound\") {\n return textError(`No symbol named \"${args.symbol}\". Use \\`gtkx_search_api\\` to find the right name.`);\n }\n\n if (result.outcome === \"ambiguous\") {\n return textError(\n `\"${args.symbol}\" matches several symbols. Pass a qualified name or a kind:\\n` +\n formatCandidates(result.candidates),\n );\n }\n\n return textContent(result.markdown);\n};\n\nconst listApiTool = (provider: ReferenceProvider): Tool =>\n defineTool({\n name: \"gtkx_list_api\",\n title: \"List API reference\",\n kind: \"readOnly\",\n description:\n \"List the project's generated GTK4 bindings API (`@gtkx/gi` and `@gtkx/jsx`). Without a namespace, \" +\n \"returns every namespace with symbol counts; with a namespace, lists all of its symbols grouped by kind.\",\n inputSchema: listApiShape,\n handler: ({ namespace, projectRoot }) =>\n scopedResult(provider, projectRoot, (reference) => listApiResult(reference, namespace)),\n });\n\nconst searchApiTool = (provider: ReferenceProvider): Tool =>\n defineTool({\n name: \"gtkx_search_api\",\n title: \"Search API reference\",\n kind: \"readOnly\",\n description:\n \"Search the project's generated GTK4 bindings API by symbol name. Returns matching symbols with \" +\n \"their namespace, kind, and a one-line summary; fetch full pages with `gtkx_get_api_docs`.\",\n inputSchema: searchApiShape,\n handler: (args) => scopedResult(provider, args.projectRoot, (reference) => searchApiResult(reference, args)),\n });\n\nconst getApiDocsTool = (provider: ReferenceProvider): Tool =>\n defineTool({\n name: \"gtkx_get_api_docs\",\n title: \"Get API docs\",\n kind: \"readOnly\",\n description:\n \"Get the full reference page for one symbol of the project's generated GTK4 bindings: JSX elements \" +\n \"(props, signals, methods) or `@gtkx/gi` classes, interfaces, records, enums, callbacks, aliases, \" +\n \"functions, and constants.\",\n inputSchema: apiDocsShape,\n handler: (args) => scopedResult(provider, args.projectRoot, (reference) => apiDocsResult(reference, args)),\n });\n\nconst buildReferenceTools = (provider: ReferenceProvider): Tool[] => [\n listApiTool(provider),\n searchApiTool(provider),\n getApiDocsTool(provider),\n];\n\nconst markdownResource = (uri: URL, text: string): ReadResourceResult => ({\n contents: [{ uri: uri.href, mimeType: \"text/markdown\", text }],\n});\n\nconst variableValue = (value: string | string[] | undefined): string =>\n Array.isArray(value) ? (value[0] ?? \"\") : (value ?? \"\");\n\nconst withLoadFallback = async <T>(load: () => Promise<T>, fallback: T): Promise<T> => {\n try {\n return await load();\n } catch {\n return fallback;\n }\n};\n\nconst completeNames = (\n provider: ReferenceProvider,\n value: string,\n collect: (reference: ReferenceApi) => string[],\n): Promise<string[]> =>\n withLoadFallback(async () => {\n const { reference } = await provider.get();\n\n return collect(reference).filter((name) => name.toLowerCase().startsWith(value.toLowerCase()));\n }, []);\n\nconst namespaceCompleter =\n (provider: ReferenceProvider) =>\n (value: string): Promise<string[]> =>\n completeNames(provider, value, (reference) => reference.namespaces().map((summary) => summary.name));\n\nconst completeSymbol = (provider: ReferenceProvider, namespace: string, value: string): Promise<string[]> => {\n if (namespace.length === 0) {\n return Promise.resolve([]);\n }\n\n return completeNames(provider, value, (reference) => reference.symbolNames(namespace));\n};\n\nconst resourceNotFound = (message: string): McpError => new McpError(ErrorCode.InvalidParams, message);\n\nconst symbolPage = async (\n uri: URL,\n provider: ReferenceProvider,\n namespace: string,\n symbol: string,\n): Promise<ReadResourceResult> => {\n const { reference } = await provider.get();\n const result = reference.lookup(`${namespace}.${symbol}`);\n\n if (result.outcome === \"page\") {\n return markdownResource(uri, result.markdown);\n }\n\n if (result.outcome === \"ambiguous\") {\n throw resourceNotFound(\n `\"${namespace}.${symbol}\" matches several symbols:\\n${formatCandidates(result.candidates)}`,\n );\n }\n\n throw resourceNotFound(`No symbol named \"${namespace}.${symbol}\"`);\n};\n\nconst registerIndexResource = (server: ResourceServer, provider: ReferenceProvider): void => {\n server.registerResource(\n \"gtkx-api-reference\",\n \"gtkx://reference/index\",\n {\n title: \"GTKX API reference index\",\n description: \"Namespaces of the project's generated GTK4 bindings, with symbol and JSX element counts.\",\n mimeType: \"text/markdown\",\n },\n async (uri) => {\n const { reference } = await provider.get();\n\n return markdownResource(uri, reference.overview());\n },\n );\n};\n\nconst registerNamespaceResource = (server: ResourceServer, provider: ReferenceProvider): void => {\n server.registerResource(\n \"gtkx-api-namespace\",\n new ResourceTemplate(\"gtkx://reference/{namespace}\", {\n list: () =>\n withLoadFallback(\n async () => {\n const { reference } = await provider.get();\n\n return {\n resources: reference.namespaces().map((summary) => ({\n uri: `gtkx://reference/${summary.name}`,\n name: `${summary.name} namespace reference`,\n mimeType: \"text/markdown\",\n })),\n };\n },\n { resources: [] },\n ),\n complete: {\n namespace: namespaceCompleter(provider),\n },\n }),\n {\n title: \"GTKX namespace reference\",\n description: \"All symbols of one namespace of the project's generated GTK4 bindings, grouped by kind.\",\n mimeType: \"text/markdown\",\n },\n async (uri, variables) => {\n const namespace = variableValue(variables.namespace);\n const { reference } = await provider.get();\n const overview = reference.namespaceOverview(namespace);\n\n if (overview === undefined) {\n throw resourceNotFound(`Unknown namespace \"${namespace}\"`);\n }\n\n return markdownResource(uri, overview);\n },\n );\n};\n\nconst registerSymbolResource = (server: ResourceServer, provider: ReferenceProvider): void => {\n server.registerResource(\n \"gtkx-api-symbol\",\n new ResourceTemplate(\"gtkx://reference/{namespace}/{symbol}\", {\n list: undefined,\n complete: {\n namespace: namespaceCompleter(provider),\n symbol: (value, context) =>\n completeSymbol(provider, variableValue(context?.arguments?.namespace), value),\n },\n }),\n {\n title: \"GTKX symbol reference\",\n description:\n \"Reference page for one symbol of the project's generated GTK4 bindings: a JSX element or a \" +\n \"class, interface, record, enum, callback, alias, function, or constant.\",\n mimeType: \"text/markdown\",\n },\n (uri, variables) =>\n symbolPage(uri, provider, variableValue(variables.namespace), variableValue(variables.symbol)),\n );\n};\n\nconst registerReferenceResources = (server: ResourceServer, provider: ReferenceProvider): void => {\n registerIndexResource(server, provider);\n registerNamespaceResource(server, provider);\n registerSymbolResource(server, provider);\n};\n\nexport {\n createReferenceProvider,\n buildReferenceTools,\n registerReferenceResources,\n type ReferenceProvider,\n};\n"]}
|
package/dist/server.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAGA,OAAO,EAAyC,KAAK,MAAM,EAAE,MAAM,aAAa,CAAC;AAsCjF,KAAK,aAAa,GAAG;IACjB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,UAAU,CAAC,EAAE,OAAO,CAAC;CACxB,CAAC;
|
|
1
|
+
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAGA,OAAO,EAAyC,KAAK,MAAM,EAAE,MAAM,aAAa,CAAC;AAsCjF,KAAK,aAAa,GAAG;IACjB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,UAAU,CAAC,EAAE,OAAO,CAAC;CACxB,CAAC;AAqBF,QAAA,MAAM,GAAG,EAAE,MAA4B,CAAC;AA0exC,QAAA,MAAM,eAAe,GAAI,MAAM,MAAM,EAAE,KAAG,aAgBzC,CAAC;AAEF,iBAAe,IAAI,CAAC,OAAO,GAAE,aAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAS9D;AAED,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,IAAI,YAAY,EAAE,eAAe,EAAE,CAAC"}
|
package/dist/server.js
CHANGED
|
@@ -8,8 +8,9 @@ import { z } from "zod";
|
|
|
8
8
|
import packageManifest from "../package.json" with { type: "json" };
|
|
9
9
|
import { AppRouter } from "./app-router.js";
|
|
10
10
|
import { ConnectionRegistry } from "./connection-registry.js";
|
|
11
|
-
import {
|
|
11
|
+
import { DEFAULT_SUBTREE_DEPTH, fireEventParams, MAX_SUBTREE_WIDGETS, queryParams, screenshotParams, treeParams, typeParams, widgetIdParams, widgetPropsParams, } from "./protocol/schemas.js";
|
|
12
12
|
import { buildReferenceTools, createReferenceProvider, registerReferenceResources, } from "./reference.js";
|
|
13
|
+
import { resolveMcpSocketAddress } from "./socket-path.js";
|
|
13
14
|
import { SocketServer } from "./socket-server.js";
|
|
14
15
|
import { selectTools } from "./tool-filter.js";
|
|
15
16
|
import { defineTool, imageContent, registerTool, textContent, textError } from "./tool.js";
|
|
@@ -18,17 +19,23 @@ const log = createLogger("mcp");
|
|
|
18
19
|
const DEFAULT_SETTINGS = { tools: [], isReadOnly: false };
|
|
19
20
|
const INSTRUCTIONS = "The widget tools drive a GTKX app running under `gtkx dev`: they read " +
|
|
20
21
|
"its live widget tree, query it by accessible role and name, click and type, and capture screenshots. " +
|
|
21
|
-
"They
|
|
22
|
+
"They wait briefly for a starting app, so start `gtkx dev` before or alongside a widget request. " +
|
|
23
|
+
"The reference tools answer from the " +
|
|
22
24
|
"bindings generated for a specific project, so they describe that project's GIR libraries rather than " +
|
|
23
25
|
"GTK in general; prefer them over recalled GTK knowledge, which is usually C, PyGObject or GJS and " +
|
|
24
26
|
"does not apply here.\n\n" +
|
|
25
27
|
"Widget IDs are valid only while the widget is mounted. After a dialog closes, a list re-renders, or " +
|
|
26
28
|
"fast refresh patches a component, re-read the tree or re-run the query instead of reusing an ID.";
|
|
27
|
-
const APPLICATION_ID_DESCRIPTION = "Application ID to query. If not specified, uses the first connected app."
|
|
29
|
+
const APPLICATION_ID_DESCRIPTION = "Application ID to query. If not specified, uses the first connected app. The tool waits briefly for the " +
|
|
30
|
+
"requested app to register.";
|
|
31
|
+
const APP_TIMEOUT_DESCRIPTION = "Milliseconds to wait for the requested app to register (default: 10000).";
|
|
28
32
|
const WIDGET_ID_DESCRIPTION = "Widget ID obtained from `gtkx_get_widget_tree`, `gtkx_query_widgets`, or `gtkx_get_widget_props`. " +
|
|
29
33
|
"IDs are scoped to a single app. An ID stays valid for as long as its widget is mounted and stops " +
|
|
30
34
|
"resolving once the widget is unmounted.";
|
|
31
|
-
const applicationIdShape = {
|
|
35
|
+
const applicationIdShape = {
|
|
36
|
+
applicationId: z.string().optional().describe(APPLICATION_ID_DESCRIPTION),
|
|
37
|
+
appTimeout: z.number().int().nonnegative().optional().describe(APP_TIMEOUT_DESCRIPTION),
|
|
38
|
+
};
|
|
32
39
|
const widgetIdShape = {
|
|
33
40
|
...applicationIdShape,
|
|
34
41
|
...describeParams(widgetIdParams.shape, { widgetId: WIDGET_ID_DESCRIPTION }),
|
|
@@ -137,7 +144,7 @@ const listAppsTool = (appRouter) => defineTool({
|
|
|
137
144
|
inputSchema: listAppsShape,
|
|
138
145
|
handler: async ({ waitForApps, timeout }) => {
|
|
139
146
|
if (waitForApps && !appRouter.hasConnectedApps()) {
|
|
140
|
-
await appRouter.waitForApp(timeout);
|
|
147
|
+
await appRouter.waitForApp(undefined, timeout);
|
|
141
148
|
}
|
|
142
149
|
const apps = appRouter.getApps();
|
|
143
150
|
const appsWithWindows = await Promise.all(apps.map((app) => appWithWindows(appRouter, app)));
|
|
@@ -165,8 +172,8 @@ const screenshotTool = (appRouter) => defineTool({
|
|
|
165
172
|
"the PNG to `path` on the app's machine. You can't target widgets from a screenshot; use " +
|
|
166
173
|
"`gtkx_get_widget_tree` to find widget IDs for interaction.",
|
|
167
174
|
inputSchema: screenshotShape,
|
|
168
|
-
handler: async ({ applicationId, returnImage, ...params }) => {
|
|
169
|
-
const result = await appRouter.sendToApp(applicationId, "widget.screenshot", params);
|
|
175
|
+
handler: async ({ applicationId, appTimeout, returnImage, ...params }) => {
|
|
176
|
+
const result = await appRouter.sendToApp(applicationId, "widget.screenshot", params, appTimeout);
|
|
170
177
|
return screenshotResult(result, returnImage !== false);
|
|
171
178
|
},
|
|
172
179
|
});
|
|
@@ -187,8 +194,8 @@ const widgetPropsTool = (appRouter) => defineTool({
|
|
|
187
194
|
"a property the widget does not have fails; a value that cannot be marshalled carries a `note` " +
|
|
188
195
|
"instead.",
|
|
189
196
|
inputSchema: widgetPropsShape,
|
|
190
|
-
handler: async ({ applicationId, ...params }) => {
|
|
191
|
-
const result = await appRouter.sendToApp(applicationId, "widget.getProps", params);
|
|
197
|
+
handler: async ({ applicationId, appTimeout, ...params }) => {
|
|
198
|
+
const result = await appRouter.sendToApp(applicationId, "widget.getProps", params, appTimeout);
|
|
192
199
|
return textContent(JSON.stringify(result, null, 2));
|
|
193
200
|
},
|
|
194
201
|
});
|
|
@@ -203,11 +210,11 @@ function buildInspectionTools(appRouter) {
|
|
|
203
210
|
"types, roles, and properties. For large apps, pass `maxDepth` for a shallow overview and/or " +
|
|
204
211
|
"`rootId` to render just one subtree instead of the whole (possibly truncated) tree.",
|
|
205
212
|
inputSchema: treeShape,
|
|
206
|
-
handler: async ({ applicationId, rootId, maxDepth }) => {
|
|
213
|
+
handler: async ({ applicationId, appTimeout, rootId, maxDepth }) => {
|
|
207
214
|
const result = await appRouter.sendToApp(applicationId, "widget.getTree", {
|
|
208
215
|
rootId,
|
|
209
216
|
maxDepth,
|
|
210
|
-
});
|
|
217
|
+
}, appTimeout);
|
|
211
218
|
return textContent(result.tree);
|
|
212
219
|
},
|
|
213
220
|
}),
|
|
@@ -220,8 +227,8 @@ function buildInspectionTools(appRouter) {
|
|
|
220
227
|
"children carries `hiddenChildren`, the count of its direct children left out. Read a " +
|
|
221
228
|
"match's subtree with `gtkx_get_widget_props` or `gtkx_get_widget_tree`.",
|
|
222
229
|
inputSchema: queryWidgetsShape,
|
|
223
|
-
handler: async ({ applicationId, ...params }) => {
|
|
224
|
-
const result = await appRouter.sendToApp(applicationId, "widget.query", params);
|
|
230
|
+
handler: async ({ applicationId, appTimeout, ...params }) => {
|
|
231
|
+
const result = await appRouter.sendToApp(applicationId, "widget.query", params, appTimeout);
|
|
225
232
|
return textContent(JSON.stringify(result, null, 2));
|
|
226
233
|
},
|
|
227
234
|
}),
|
|
@@ -239,8 +246,8 @@ function buildInteractionTools(appRouter) {
|
|
|
239
246
|
"buttons, checkboxes, switches, list and grid rows, tree expanders, and column headers: a " +
|
|
240
247
|
"row is selected, an expander toggles its row's expansion, and a header sorts its column.",
|
|
241
248
|
inputSchema: widgetIdShape,
|
|
242
|
-
handler: async ({ applicationId, ...params }) => {
|
|
243
|
-
await appRouter.sendToApp(applicationId, "widget.click", params);
|
|
249
|
+
handler: async ({ applicationId, appTimeout, ...params }) => {
|
|
250
|
+
await appRouter.sendToApp(applicationId, "widget.click", params, appTimeout);
|
|
244
251
|
return textContent("Clicked");
|
|
245
252
|
},
|
|
246
253
|
}),
|
|
@@ -250,8 +257,8 @@ function buildInteractionTools(appRouter) {
|
|
|
250
257
|
kind: "action",
|
|
251
258
|
description: "Type text into an editable widget like Entry or TextView",
|
|
252
259
|
inputSchema: typeShape,
|
|
253
|
-
handler: async ({ applicationId, ...params }) => {
|
|
254
|
-
await appRouter.sendToApp(applicationId, "widget.type", params);
|
|
260
|
+
handler: async ({ applicationId, appTimeout, ...params }) => {
|
|
261
|
+
await appRouter.sendToApp(applicationId, "widget.type", params, appTimeout);
|
|
255
262
|
return textContent("Typed text");
|
|
256
263
|
},
|
|
257
264
|
}),
|
|
@@ -261,8 +268,8 @@ function buildInteractionTools(appRouter) {
|
|
|
261
268
|
kind: "action",
|
|
262
269
|
description: "Emit a GTK4 signal on a widget. Use this for custom interactions.",
|
|
263
270
|
inputSchema: fireEventShape,
|
|
264
|
-
handler: async ({ applicationId, ...params }) => {
|
|
265
|
-
const result = await appRouter.sendToApp(applicationId, "widget.fireEvent", params);
|
|
271
|
+
handler: async ({ applicationId, appTimeout, ...params }) => {
|
|
272
|
+
const result = await appRouter.sendToApp(applicationId, "widget.fireEvent", params, appTimeout);
|
|
266
273
|
return textContent(JSON.stringify(result, null, 2));
|
|
267
274
|
},
|
|
268
275
|
}),
|
|
@@ -280,34 +287,74 @@ const registerTools = (mcpServer, appRouter, provider, settings) => {
|
|
|
280
287
|
registerTool(mcpServer, tool);
|
|
281
288
|
}
|
|
282
289
|
};
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
290
|
+
const stoppedServerError = () => new Error("createMcpServer: a stopped server cannot be started again");
|
|
291
|
+
const wasStopRequested = (state) => state.isStopRequested;
|
|
292
|
+
function stopServer(state) {
|
|
293
|
+
if (state.shutdown !== null) {
|
|
294
|
+
return state.shutdown;
|
|
286
295
|
}
|
|
287
|
-
state.
|
|
288
|
-
|
|
289
|
-
|
|
296
|
+
state.isStopRequested = true;
|
|
297
|
+
state.appRouter.dispose();
|
|
298
|
+
const startup = state.startup;
|
|
299
|
+
const shutdown = (async () => {
|
|
300
|
+
if (startup !== null) {
|
|
301
|
+
await Promise.allSettled([startup]);
|
|
302
|
+
}
|
|
303
|
+
await state.socketServer.stop();
|
|
304
|
+
await state.mcpServer.close();
|
|
305
|
+
})();
|
|
306
|
+
state.shutdown = shutdown;
|
|
307
|
+
return shutdown;
|
|
290
308
|
}
|
|
291
|
-
|
|
292
|
-
if (state
|
|
293
|
-
|
|
309
|
+
function startServer(state) {
|
|
310
|
+
if (wasStopRequested(state)) {
|
|
311
|
+
return Promise.reject(stoppedServerError());
|
|
294
312
|
}
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
return;
|
|
313
|
+
if (state.startup !== null) {
|
|
314
|
+
return state.startup;
|
|
298
315
|
}
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
316
|
+
const startup = (async () => {
|
|
317
|
+
try {
|
|
318
|
+
await state.socketServer.start();
|
|
319
|
+
if (wasStopRequested(state)) {
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
log.info(`socket server listening on ${state.socketPath}`);
|
|
323
|
+
await connectStdio(state.mcpServer, () => stopServer(state));
|
|
324
|
+
}
|
|
325
|
+
catch (error) {
|
|
326
|
+
if (!wasStopRequested(state)) {
|
|
327
|
+
state.isStopRequested = true;
|
|
328
|
+
state.appRouter.dispose();
|
|
329
|
+
await state.socketServer.stop();
|
|
330
|
+
await state.mcpServer.close();
|
|
331
|
+
}
|
|
332
|
+
throw error;
|
|
333
|
+
}
|
|
334
|
+
})();
|
|
335
|
+
state.startup = startup;
|
|
336
|
+
return startup;
|
|
302
337
|
}
|
|
303
|
-
const createServerHandle = (socketServer, mcpServer, socketPath) => {
|
|
304
|
-
const state = {
|
|
338
|
+
const createServerHandle = (socketServer, mcpServer, appRouter, socketPath) => {
|
|
339
|
+
const state = {
|
|
340
|
+
socketServer,
|
|
341
|
+
mcpServer,
|
|
342
|
+
appRouter,
|
|
343
|
+
socketPath,
|
|
344
|
+
isStopRequested: false,
|
|
345
|
+
startup: null,
|
|
346
|
+
shutdown: null,
|
|
347
|
+
};
|
|
305
348
|
return { start: () => startServer(state), stop: () => stopServer(state) };
|
|
306
349
|
};
|
|
307
350
|
const createMcpServer = (options) => {
|
|
308
|
-
const
|
|
351
|
+
const socketAddress = resolveMcpSocketAddress(options.socketPath);
|
|
352
|
+
const socketPath = socketAddress.path;
|
|
353
|
+
if (socketAddress.fallbackDirectory !== null) {
|
|
354
|
+
log.warn(`MCP socket path exceeds the safe Unix byte budget; using private fallback ${socketPath}`);
|
|
355
|
+
}
|
|
309
356
|
const registry = new ConnectionRegistry();
|
|
310
|
-
const socketServer = new SocketServer(registry,
|
|
357
|
+
const socketServer = new SocketServer(registry, socketAddress);
|
|
311
358
|
const appRouter = new AppRouter(registry);
|
|
312
359
|
registry.addEventListener("error", logSocketError);
|
|
313
360
|
appRouter.addEventListener("appRegistered", (event) => {
|
|
@@ -321,7 +368,7 @@ const createMcpServer = (options) => {
|
|
|
321
368
|
const referenceProvider = createReferenceProvider({ getAppRoot: () => appRouter.getProjectRoot() });
|
|
322
369
|
registerTools(mcpServer, appRouter, referenceProvider, options.settings ?? DEFAULT_SETTINGS);
|
|
323
370
|
registerReferenceResources(mcpServer, referenceProvider);
|
|
324
|
-
return createServerHandle(socketServer, mcpServer, socketPath);
|
|
371
|
+
return createServerHandle(socketServer, mcpServer, appRouter, socketPath);
|
|
325
372
|
};
|
|
326
373
|
const configuredSettings = async (cwd) => {
|
|
327
374
|
try {
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAoB,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC7E,OAAO,EAAE,YAAY,EAAE,uBAAuB,EAAe,MAAM,aAAa,CAAC;AACjF,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAA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EAAE;IACtD,MAAM,EAAE,MAAM,EAAE,GAAG,SAAS,CAAC;QACzB,IAAI,EAAE,IAAI;QACV,OAAO,EAAE;YACL,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE;YACzC,WAAW,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE;SACnC;QACD,gBAAgB,EAAE,KAAK;KAC1B,CAAC,CAAC;IAEH,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,aAAa,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAEnF,OAAO;QACH,GAAG,CAAC,KAAK,KAAK,SAAS,IAAI,EAAE,KAAK,EAAE,CAAC;QACrC,GAAG,CAAC,MAAM,CAAC,WAAW,CAAC,KAAK,SAAS,IAAI,EAAE,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC;KAChF,CAAC;AACN,CAAC,CAAC;AAEF,KAAK,UAAU,IAAI,CAAC,UAAyB,EAAE;IAC3C,MAAM,QAAQ,GAAG,MAAM,eAAe,CAAC,OAAO,CAAC,CAAC;IAChD,MAAM,MAAM,GAAG,eAAe,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;IAEtD,uBAAuB,CAAC;QACpB,QAAQ,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE;KAChC,CAAC,CAAC;IAEH,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;AACzB,CAAC;AAED,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,IAAI,YAAY,EAAE,eAAe,EAAE,CAAC","sourcesContent":["import type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { loadConfig } from \"@gtkx/config\";\nimport { type McpSettings, resolveMcpSettings } from \"@gtkx/config/internal\";\nimport { createLogger, installGracefulShutdown, type Logger } from \"@gtkx/utils\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { parseArgs } from \"node:util\";\nimport { z } from \"zod\";\nimport type { ConnectionErrorEvent } from \"./transport.js\";\nimport packageManifest from \"../package.json\" with { type: \"json\" };\nimport { type AppRegisteredEvent, AppRouter, type AppUnregisteredEvent } from \"./app-router.js\";\nimport { ConnectionRegistry } from \"./connection-registry.js\";\nimport {\n type AppInfo,\n DEFAULT_SOCKET_PATH,\n DEFAULT_SUBTREE_DEPTH,\n fireEventParams,\n MAX_SUBTREE_WIDGETS,\n queryParams,\n screenshotParams,\n treeParams,\n typeParams,\n widgetIdParams,\n widgetPropsParams,\n} from \"./protocol/schemas.js\";\nimport {\n buildReferenceTools,\n createReferenceProvider,\n type ReferenceProvider,\n registerReferenceResources,\n} from \"./reference.js\";\nimport { SocketServer } from \"./socket-server.js\";\nimport { selectTools } from \"./tool-filter.js\";\nimport { defineTool, imageContent, registerTool, textContent, textError, type Tool } from \"./tool.js\";\n\ntype CreateMcpServerOptions = {\n socketPath?: string;\n version: string;\n settings?: McpSettings;\n};\n\ntype ServerOptions = {\n cwd?: string;\n tools?: string[];\n isReadOnly?: boolean;\n};\n\ntype McpServerHandle = {\n start(): Promise<void>;\n stop(): Promise<void>;\n};\n\ntype ServerLifecycle = {\n socketServer: SocketServer;\n mcpServer: McpServer;\n socketPath: string;\n isStopped: boolean;\n isStarted: boolean;\n};\n\ntype AppWindow = { id: string; title: string | null };\ntype AppWithWindows = AppInfo & { windows?: AppWindow[] };\n\nconst { version } = packageManifest;\nconst log: Logger = createLogger(\"mcp\");\nconst DEFAULT_SETTINGS: McpSettings = { tools: [], isReadOnly: false };\n\nconst INSTRUCTIONS =\n \"The widget tools drive a GTKX app running under `gtkx dev`: they read \" +\n \"its live widget tree, query it by accessible role and name, click and type, and capture screenshots. \" +\n \"They fail until an app is running, so start `gtkx dev` first. The reference tools answer from the \" +\n \"bindings generated for a specific project, so they describe that project's GIR libraries rather than \" +\n \"GTK in general; prefer them over recalled GTK knowledge, which is usually C, PyGObject or GJS and \" +\n \"does not apply here.\\n\\n\" +\n \"Widget IDs are valid only while the widget is mounted. After a dialog closes, a list re-renders, or \" +\n \"fast refresh patches a component, re-read the tree or re-run the query instead of reusing an ID.\";\n\nconst APPLICATION_ID_DESCRIPTION = \"Application ID to query. If not specified, uses the first connected app.\";\n\nconst WIDGET_ID_DESCRIPTION =\n \"Widget ID obtained from `gtkx_get_widget_tree`, `gtkx_query_widgets`, or `gtkx_get_widget_props`. \" +\n \"IDs are scoped to a single app. An ID stays valid for as long as its widget is mounted and stops \" +\n \"resolving once the widget is unmounted.\";\n\nconst applicationIdShape = { applicationId: z.string().optional().describe(APPLICATION_ID_DESCRIPTION) };\n\nconst widgetIdShape = {\n ...applicationIdShape,\n ...describeParams(widgetIdParams.shape, { widgetId: WIDGET_ID_DESCRIPTION }),\n};\n\nconst widgetPropsShape = {\n ...applicationIdShape,\n ...describeParams(widgetPropsParams.shape, {\n widgetId: WIDGET_ID_DESCRIPTION,\n properties:\n \"GObject property names to read as well, in kebab-case or camelCase (\\\"current-breakpoint\\\" or \" +\n \"\\\"currentBreakpoint\\\"). Omit for the summary alone.\",\n maxDepth:\n `How many levels of descendants to include: ${String(DEFAULT_SUBTREE_DEPTH)} by default, and 0 ` +\n `for the widget on its own. At most ${String(MAX_SUBTREE_WIDGETS)} widgets come back whatever ` +\n \"the depth, and any widget whose own direct children were left out carries a `hiddenChildren` count.\",\n }),\n};\n\nconst treeShape = {\n ...applicationIdShape,\n ...describeParams(treeParams.shape, {\n rootId:\n \"Render only the subtree rooted at this widget ID (from a prior tree or query). Omit for the \" +\n \"whole app.\",\n maxDepth:\n \"Limit how many levels deep to render, and 0 for the root widget on its own; deeper \" +\n \"descendants are summarized with a count. Combine with rootId to drill in without dumping \" +\n \"the whole tree.\",\n }),\n};\n\nconst listAppsShape = {\n waitForApps: z\n .boolean()\n .optional()\n .describe(\n \"If true, wait for at least one app to register before returning. Useful when app is still starting.\",\n ),\n timeout: z.number().optional().describe(\"Timeout in milliseconds when waitForApps is true (default: 10000)\"),\n};\n\nconst queryWidgetsShape = {\n ...applicationIdShape,\n ...describeParams(queryParams.shape, {\n by: \"Query type\",\n value: \"Value to search for\",\n options: \"Additional query options\",\n }),\n};\n\nconst typeShape = {\n ...applicationIdShape,\n ...describeParams(typeParams.shape, {\n widgetId: WIDGET_ID_DESCRIPTION,\n text: \"Text to type\",\n clear: \"Clear existing text before typing\",\n }),\n};\n\nconst fireEventShape = {\n ...applicationIdShape,\n ...describeParams(fireEventParams.shape, {\n widgetId: WIDGET_ID_DESCRIPTION,\n signal: \"GTK4 signal name to emit\",\n args: \"Arguments to pass to the signal\",\n }),\n};\n\nconst screenshotShape = {\n ...applicationIdShape,\n ...describeParams(screenshotParams.shape, {\n windowId: \"Window ID to capture. If not specified, captures the first window.\",\n path:\n \"Absolute path to write the PNG to on the app's machine. If set, the screenshot is saved there \" +\n \"in addition to being returned.\",\n }),\n returnImage: z\n .boolean()\n .optional()\n .describe(\n \"Whether to return the PNG as image content, true by default. Pass false together with `path` \" +\n \"to save the screenshot and get back only where it landed, which keeps the image out of the \" +\n \"conversation until something actually needs to look at it.\",\n ),\n};\n\nfunction describeParams<Shape extends Record<string, z.ZodType>>(\n shape: Shape,\n descriptions: { [Key in keyof Shape]: string },\n): Shape {\n const described: [string, z.ZodType][] = Object.entries(shape).map(([key, schema]) => [\n key,\n schema.describe(descriptions[key as keyof Shape]),\n ]);\n\n return Object.fromEntries(described) as Shape;\n}\n\nconst connectStdio = async (mcpServer: McpServer, stop: () => Promise<void>): Promise<void> => {\n const transport = new StdioServerTransport();\n process.stdin.on(\"end\", () => void stop());\n process.stdin.on(\"close\", () => void stop());\n await mcpServer.connect(transport);\n};\n\nconst logSocketError = (event: Event): void => {\n const error = (event as ConnectionErrorEvent).detail;\n const code = (error as NodeJS.ErrnoException).code;\n\n if (code === \"EPIPE\" || code === \"ECONNRESET\") {\n return;\n }\n\n log.error(`socket error: ${error.message}`);\n};\n\nconst appWithWindows = async (appRouter: AppRouter, app: AppInfo): Promise<AppWithWindows> => {\n try {\n const result = await appRouter.sendToApp<{ windows: AppWindow[] }>(\n app.applicationId,\n \"app.getWindows\",\n {},\n );\n\n return { ...app, windows: result.windows };\n } catch {\n return app;\n }\n};\n\nconst listAppsTool = (appRouter: AppRouter): Tool =>\n defineTool({\n name: \"gtkx_list_apps\",\n title: \"List apps\",\n kind: \"readOnly\",\n description: \"List all connected GTKX applications and their open windows.\",\n inputSchema: listAppsShape,\n handler: async ({ waitForApps, timeout }) => {\n if (waitForApps && !appRouter.hasConnectedApps()) {\n await appRouter.waitForApp(timeout);\n }\n\n const apps = appRouter.getApps();\n const appsWithWindows = await Promise.all(apps.map((app) => appWithWindows(appRouter, app)));\n\n return textContent(JSON.stringify(appsWithWindows, null, 2));\n },\n });\n\nconst screenshotResult = (\n result: { data: string; mimeType: string; savedPath?: string },\n shouldReturnImage: boolean,\n): CallToolResult => {\n if (result.savedPath === undefined) {\n return shouldReturnImage\n ? imageContent(result.data, result.mimeType)\n : textError(\n \"Nothing to return: `returnImage` was false and no `path` was given, so the screenshot was \" +\n \"neither saved nor returned. Pass `path` to save it, or leave `returnImage` unset.\",\n );\n }\n\n const saved = { type: \"text\", text: `Screenshot saved to ${result.savedPath}` } as const;\n\n if (!shouldReturnImage) {\n return { content: [saved] };\n }\n\n return { content: [saved, { type: \"image\", data: result.data, mimeType: result.mimeType }] };\n};\n\nconst screenshotTool = (appRouter: AppRouter): Tool =>\n defineTool({\n name: \"gtkx_take_screenshot\",\n title: \"Take screenshot\",\n kind: \"readOnly\",\n description:\n \"Capture a screenshot of a window. Returns base64-encoded PNG image data, and optionally writes \" +\n \"the PNG to `path` on the app's machine. You can't target widgets from a screenshot; use \" +\n \"`gtkx_get_widget_tree` to find widget IDs for interaction.\",\n inputSchema: screenshotShape,\n handler: async ({ applicationId, returnImage, ...params }) => {\n const result = await appRouter.sendToApp<{ data: string; mimeType: string; savedPath?: string }>(\n applicationId,\n \"widget.screenshot\",\n params,\n );\n\n return screenshotResult(result, returnImage !== false);\n },\n });\n\nconst widgetPropsTool = (appRouter: AppRouter): Tool =>\n defineTool({\n name: \"gtkx_get_widget_props\",\n title: \"Get widget properties\",\n kind: \"readOnly\",\n description:\n \"Get a fixed summary of one widget by ID: type, accessible role, name, text, sensitivity, \" +\n \"visibility, CSS classes, and the same summary for its descendants. The subtree is bounded \" +\n `twice: ${String(DEFAULT_SUBTREE_DEPTH)} levels deep unless \\`maxDepth\\` says otherwise, and ` +\n `${String(MAX_SUBTREE_WIDGETS)} widgets in all, filled breadth first. Wherever either bound ` +\n \"cut a branch, that widget carries `hiddenChildren`, the count of its own direct children left \" +\n \"out rather than of everything below them; call again with that widget's ID to drill in, or \" +\n \"use `gtkx_get_widget_tree` for a wider map. Pass `properties` to read GObject properties too; \" +\n \"they come back first in the payload, each under its canonical kebab-case name as \" +\n \"`{type, value}`, where an enum or flags value is its GType value name, a 64-bit integer a \" +\n \"decimal string, and an object its GType name plus `widgetId` when it is a widget. Asking for \" +\n \"a property the widget does not have fails; a value that cannot be marshalled carries a `note` \" +\n \"instead.\",\n inputSchema: widgetPropsShape,\n handler: async ({ applicationId, ...params }) => {\n const result = await appRouter.sendToApp(applicationId, \"widget.getProps\", params);\n\n return textContent(JSON.stringify(result, null, 2));\n },\n });\n\nfunction buildInspectionTools(appRouter: AppRouter): Tool[] {\n return [\n listAppsTool(appRouter),\n defineTool({\n name: \"gtkx_get_widget_tree\",\n title: \"Widget tree\",\n kind: \"readOnly\",\n description:\n \"Get the widget hierarchy for a connected GTKX app. Returns a tree of widgets with their IDs, \" +\n \"types, roles, and properties. For large apps, pass `maxDepth` for a shallow overview and/or \" +\n \"`rootId` to render just one subtree instead of the whole (possibly truncated) tree.\",\n inputSchema: treeShape,\n handler: async ({ applicationId, rootId, maxDepth }) => {\n const result = await appRouter.sendToApp<{ tree: string }>(applicationId, \"widget.getTree\", {\n rootId,\n maxDepth,\n });\n\n return textContent(result.tree);\n },\n }),\n defineTool({\n name: \"gtkx_query_widgets\",\n title: \"Query widgets\",\n kind: \"readOnly\",\n description:\n \"Find widgets by role, text, name, or label. Returns each match with its ID and the same \" +\n \"fixed summary `gtkx_get_widget_props` returns, with no descendants: a match that has \" +\n \"children carries `hiddenChildren`, the count of its direct children left out. Read a \" +\n \"match's subtree with `gtkx_get_widget_props` or `gtkx_get_widget_tree`.\",\n inputSchema: queryWidgetsShape,\n handler: async ({ applicationId, ...params }) => {\n const result = await appRouter.sendToApp(applicationId, \"widget.query\", params);\n\n return textContent(JSON.stringify(result, null, 2));\n },\n }),\n widgetPropsTool(appRouter),\n screenshotTool(appRouter),\n ];\n}\n\nfunction buildInteractionTools(appRouter: AppRouter): Tool[] {\n return [\n defineTool({\n name: \"gtkx_click\",\n title: \"Click widget\",\n kind: \"action\",\n description:\n \"Click a widget through userEvent.click, with no special case per widget. Works with \" +\n \"buttons, checkboxes, switches, list and grid rows, tree expanders, and column headers: a \" +\n \"row is selected, an expander toggles its row's expansion, and a header sorts its column.\",\n inputSchema: widgetIdShape,\n handler: async ({ applicationId, ...params }) => {\n await appRouter.sendToApp(applicationId, \"widget.click\", params);\n\n return textContent(\"Clicked\");\n },\n }),\n defineTool({\n name: \"gtkx_type\",\n title: \"Type text\",\n kind: \"action\",\n description: \"Type text into an editable widget like Entry or TextView\",\n inputSchema: typeShape,\n handler: async ({ applicationId, ...params }) => {\n await appRouter.sendToApp(applicationId, \"widget.type\", params);\n\n return textContent(\"Typed text\");\n },\n }),\n defineTool({\n name: \"gtkx_fire_event\",\n title: \"Fire event\",\n kind: \"action\",\n description: \"Emit a GTK4 signal on a widget. Use this for custom interactions.\",\n inputSchema: fireEventShape,\n handler: async ({ applicationId, ...params }) => {\n const result = await appRouter.sendToApp(applicationId, \"widget.fireEvent\", params);\n\n return textContent(JSON.stringify(result, null, 2));\n },\n }),\n ];\n}\n\nfunction buildTools(appRouter: AppRouter): Tool[] {\n return [...buildInspectionTools(appRouter), ...buildInteractionTools(appRouter)];\n}\n\nconst registerTools = (\n mcpServer: McpServer,\n appRouter: AppRouter,\n provider: ReferenceProvider,\n settings: McpSettings,\n): void => {\n const tools = selectTools([...buildTools(appRouter), ...buildReferenceTools(provider)], settings);\n\n if (tools.length === 0) {\n log.warn(\"no tools matched the configured filter; the server is registering none\");\n }\n\n for (const tool of tools) {\n registerTool(mcpServer, tool);\n }\n};\n\nasync function stopServer(state: ServerLifecycle): Promise<void> {\n if (state.isStopped) {\n return;\n }\n\n state.isStopped = true;\n await state.socketServer.stop();\n await state.mcpServer.close();\n}\n\nasync function startServer(state: ServerLifecycle): Promise<void> {\n if (state.isStopped) {\n throw new Error(\"createMcpServer: a stopped server cannot be started again\");\n }\n\n await state.socketServer.start();\n\n if (state.isStarted) {\n return;\n }\n\n state.isStarted = true;\n log.info(`socket server listening on ${state.socketPath}`);\n await connectStdio(state.mcpServer, () => stopServer(state));\n}\n\nconst createServerHandle = (socketServer: SocketServer, mcpServer: McpServer, socketPath: string): McpServerHandle => {\n const state: ServerLifecycle = { socketServer, mcpServer, socketPath, isStopped: false, isStarted: false };\n\n return { start: () => startServer(state), stop: () => stopServer(state) };\n};\n\nconst createMcpServer = (options: CreateMcpServerOptions): McpServerHandle => {\n const socketPath = options.socketPath ?? DEFAULT_SOCKET_PATH;\n const registry = new ConnectionRegistry();\n const socketServer = new SocketServer(registry, socketPath);\n const appRouter = new AppRouter(registry);\n registry.addEventListener(\"error\", logSocketError);\n\n appRouter.addEventListener(\"appRegistered\", (event) => {\n const appInfo = (event as AppRegisteredEvent).detail;\n log.info(`app registered: ${appInfo.applicationId} (PID: ${String(appInfo.pid)})`);\n });\n\n appRouter.addEventListener(\"appUnregistered\", (event) => {\n log.info(`app unregistered: ${(event as AppUnregisteredEvent).detail}`);\n });\n\n const mcpServer = new McpServer({ name: \"gtkx-mcp\", version: options.version }, { instructions: INSTRUCTIONS });\n const referenceProvider = createReferenceProvider({ getAppRoot: () => appRouter.getProjectRoot() });\n registerTools(mcpServer, appRouter, referenceProvider, options.settings ?? DEFAULT_SETTINGS);\n registerReferenceResources(mcpServer, referenceProvider);\n\n return createServerHandle(socketServer, mcpServer, socketPath);\n};\n\nconst configuredSettings = async (cwd: string): Promise<McpSettings> => {\n try {\n const { config } = await loadConfig(cwd);\n\n return resolveMcpSettings(config);\n } catch {\n return DEFAULT_SETTINGS;\n }\n};\n\nconst resolveSettings = async (options: ServerOptions): Promise<McpSettings> => {\n const configured = await configuredSettings(options.cwd ?? process.cwd());\n\n return {\n tools: options.tools ?? configured.tools,\n isReadOnly: options.isReadOnly ?? configured.isReadOnly,\n };\n};\n\nconst splitPatterns = (values: string[]): string[] =>\n values.flatMap((value) => value.split(\",\")).map((value) => value.trim()).filter((value) => value.length > 0);\n\nconst parseServerArgs = (argv: string[]): ServerOptions => {\n const { values } = parseArgs({\n args: argv,\n options: {\n tools: { type: \"string\", multiple: true },\n \"read-only\": { type: \"boolean\" },\n },\n allowPositionals: false,\n });\n\n const tools = values.tools === undefined ? undefined : splitPatterns(values.tools);\n\n return {\n ...(tools !== undefined && { tools }),\n ...(values[\"read-only\"] !== undefined && { isReadOnly: values[\"read-only\"] }),\n };\n};\n\nasync function main(options: ServerOptions = {}): Promise<void> {\n const settings = await resolveSettings(options);\n const server = createMcpServer({ version, settings });\n\n installGracefulShutdown({\n onSignal: () => server.stop(),\n });\n\n await server.start();\n}\n\nexport { log, main, main as runMcpServer, parseServerArgs };\n"]}
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAoB,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC7E,OAAO,EAAE,YAAY,EAAE,uBAAuB,EAAe,MAAM,aAAa,CAAC;AACjF,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,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AM,CAAC,WAAW,CAAC,KAAK,SAAS,IAAI,EAAE,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC;KAChF,CAAC;AACN,CAAC,CAAC;AAEF,KAAK,UAAU,IAAI,CAAC,UAAyB,EAAE;IAC3C,MAAM,QAAQ,GAAG,MAAM,eAAe,CAAC,OAAO,CAAC,CAAC;IAChD,MAAM,MAAM,GAAG,eAAe,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;IAEtD,uBAAuB,CAAC;QACpB,QAAQ,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE;KAChC,CAAC,CAAC;IAEH,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;AACzB,CAAC;AAED,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,IAAI,YAAY,EAAE,eAAe,EAAE,CAAC","sourcesContent":["import type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { loadConfig } from \"@gtkx/config\";\nimport { type McpSettings, resolveMcpSettings } from \"@gtkx/config/internal\";\nimport { createLogger, installGracefulShutdown, type Logger } from \"@gtkx/utils\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { parseArgs } from \"node:util\";\nimport { z } from \"zod\";\nimport type { ConnectionErrorEvent } from \"./transport.js\";\nimport packageManifest from \"../package.json\" with { type: \"json\" };\nimport { type AppRegisteredEvent, AppRouter, type AppUnregisteredEvent } from \"./app-router.js\";\nimport { ConnectionRegistry } from \"./connection-registry.js\";\nimport {\n type AppInfo,\n DEFAULT_SUBTREE_DEPTH,\n fireEventParams,\n MAX_SUBTREE_WIDGETS,\n queryParams,\n screenshotParams,\n treeParams,\n typeParams,\n widgetIdParams,\n widgetPropsParams,\n} from \"./protocol/schemas.js\";\nimport {\n buildReferenceTools,\n createReferenceProvider,\n type ReferenceProvider,\n registerReferenceResources,\n} from \"./reference.js\";\nimport { resolveMcpSocketAddress } from \"./socket-path.js\";\nimport { SocketServer } from \"./socket-server.js\";\nimport { selectTools } from \"./tool-filter.js\";\nimport { defineTool, imageContent, registerTool, textContent, textError, type Tool } from \"./tool.js\";\n\ntype CreateMcpServerOptions = {\n socketPath?: string;\n version: string;\n settings?: McpSettings;\n};\n\ntype ServerOptions = {\n cwd?: string;\n tools?: string[];\n isReadOnly?: boolean;\n};\n\ntype McpServerHandle = {\n start(): Promise<void>;\n stop(): Promise<void>;\n};\n\ntype ServerLifecycle = {\n socketServer: SocketServer;\n mcpServer: McpServer;\n appRouter: AppRouter;\n socketPath: string;\n isStopRequested: boolean;\n startup: Promise<void> | null;\n shutdown: Promise<void> | null;\n};\n\ntype AppWindow = { id: string; title: string | null };\ntype AppWithWindows = AppInfo & { windows?: AppWindow[] };\n\nconst { version } = packageManifest;\nconst log: Logger = createLogger(\"mcp\");\nconst DEFAULT_SETTINGS: McpSettings = { tools: [], isReadOnly: false };\n\nconst INSTRUCTIONS =\n \"The widget tools drive a GTKX app running under `gtkx dev`: they read \" +\n \"its live widget tree, query it by accessible role and name, click and type, and capture screenshots. \" +\n \"They wait briefly for a starting app, so start `gtkx dev` before or alongside a widget request. \" +\n \"The reference tools answer from the \" +\n \"bindings generated for a specific project, so they describe that project's GIR libraries rather than \" +\n \"GTK in general; prefer them over recalled GTK knowledge, which is usually C, PyGObject or GJS and \" +\n \"does not apply here.\\n\\n\" +\n \"Widget IDs are valid only while the widget is mounted. After a dialog closes, a list re-renders, or \" +\n \"fast refresh patches a component, re-read the tree or re-run the query instead of reusing an ID.\";\n\nconst APPLICATION_ID_DESCRIPTION =\n \"Application ID to query. If not specified, uses the first connected app. The tool waits briefly for the \" +\n \"requested app to register.\";\n\nconst APP_TIMEOUT_DESCRIPTION = \"Milliseconds to wait for the requested app to register (default: 10000).\";\n\nconst WIDGET_ID_DESCRIPTION =\n \"Widget ID obtained from `gtkx_get_widget_tree`, `gtkx_query_widgets`, or `gtkx_get_widget_props`. \" +\n \"IDs are scoped to a single app. An ID stays valid for as long as its widget is mounted and stops \" +\n \"resolving once the widget is unmounted.\";\n\nconst applicationIdShape = {\n applicationId: z.string().optional().describe(APPLICATION_ID_DESCRIPTION),\n appTimeout: z.number().int().nonnegative().optional().describe(APP_TIMEOUT_DESCRIPTION),\n};\n\nconst widgetIdShape = {\n ...applicationIdShape,\n ...describeParams(widgetIdParams.shape, { widgetId: WIDGET_ID_DESCRIPTION }),\n};\n\nconst widgetPropsShape = {\n ...applicationIdShape,\n ...describeParams(widgetPropsParams.shape, {\n widgetId: WIDGET_ID_DESCRIPTION,\n properties:\n \"GObject property names to read as well, in kebab-case or camelCase (\\\"current-breakpoint\\\" or \" +\n \"\\\"currentBreakpoint\\\"). Omit for the summary alone.\",\n maxDepth:\n `How many levels of descendants to include: ${String(DEFAULT_SUBTREE_DEPTH)} by default, and 0 ` +\n `for the widget on its own. At most ${String(MAX_SUBTREE_WIDGETS)} widgets come back whatever ` +\n \"the depth, and any widget whose own direct children were left out carries a `hiddenChildren` count.\",\n }),\n};\n\nconst treeShape = {\n ...applicationIdShape,\n ...describeParams(treeParams.shape, {\n rootId:\n \"Render only the subtree rooted at this widget ID (from a prior tree or query). Omit for the \" +\n \"whole app.\",\n maxDepth:\n \"Limit how many levels deep to render, and 0 for the root widget on its own; deeper \" +\n \"descendants are summarized with a count. Combine with rootId to drill in without dumping \" +\n \"the whole tree.\",\n }),\n};\n\nconst listAppsShape = {\n waitForApps: z\n .boolean()\n .optional()\n .describe(\n \"If true, wait for at least one app to register before returning. Useful when app is still starting.\",\n ),\n timeout: z.number().optional().describe(\"Timeout in milliseconds when waitForApps is true (default: 10000)\"),\n};\n\nconst queryWidgetsShape = {\n ...applicationIdShape,\n ...describeParams(queryParams.shape, {\n by: \"Query type\",\n value: \"Value to search for\",\n options: \"Additional query options\",\n }),\n};\n\nconst typeShape = {\n ...applicationIdShape,\n ...describeParams(typeParams.shape, {\n widgetId: WIDGET_ID_DESCRIPTION,\n text: \"Text to type\",\n clear: \"Clear existing text before typing\",\n }),\n};\n\nconst fireEventShape = {\n ...applicationIdShape,\n ...describeParams(fireEventParams.shape, {\n widgetId: WIDGET_ID_DESCRIPTION,\n signal: \"GTK4 signal name to emit\",\n args: \"Arguments to pass to the signal\",\n }),\n};\n\nconst screenshotShape = {\n ...applicationIdShape,\n ...describeParams(screenshotParams.shape, {\n windowId: \"Window ID to capture. If not specified, captures the first window.\",\n path:\n \"Absolute path to write the PNG to on the app's machine. If set, the screenshot is saved there \" +\n \"in addition to being returned.\",\n }),\n returnImage: z\n .boolean()\n .optional()\n .describe(\n \"Whether to return the PNG as image content, true by default. Pass false together with `path` \" +\n \"to save the screenshot and get back only where it landed, which keeps the image out of the \" +\n \"conversation until something actually needs to look at it.\",\n ),\n};\n\nfunction describeParams<Shape extends Record<string, z.ZodType>>(\n shape: Shape,\n descriptions: { [Key in keyof Shape]: string },\n): Shape {\n const described: [string, z.ZodType][] = Object.entries(shape).map(([key, schema]) => [\n key,\n schema.describe(descriptions[key as keyof Shape]),\n ]);\n\n return Object.fromEntries(described) as Shape;\n}\n\nconst connectStdio = async (mcpServer: McpServer, stop: () => Promise<void>): Promise<void> => {\n const transport = new StdioServerTransport();\n process.stdin.on(\"end\", () => void stop());\n process.stdin.on(\"close\", () => void stop());\n await mcpServer.connect(transport);\n};\n\nconst logSocketError = (event: Event): void => {\n const error = (event as ConnectionErrorEvent).detail;\n const code = (error as NodeJS.ErrnoException).code;\n\n if (code === \"EPIPE\" || code === \"ECONNRESET\") {\n return;\n }\n\n log.error(`socket error: ${error.message}`);\n};\n\nconst appWithWindows = async (appRouter: AppRouter, app: AppInfo): Promise<AppWithWindows> => {\n try {\n const result = await appRouter.sendToApp<{ windows: AppWindow[] }>(\n app.applicationId,\n \"app.getWindows\",\n {},\n );\n\n return { ...app, windows: result.windows };\n } catch {\n return app;\n }\n};\n\nconst listAppsTool = (appRouter: AppRouter): Tool =>\n defineTool({\n name: \"gtkx_list_apps\",\n title: \"List apps\",\n kind: \"readOnly\",\n description: \"List all connected GTKX applications and their open windows.\",\n inputSchema: listAppsShape,\n handler: async ({ waitForApps, timeout }) => {\n if (waitForApps && !appRouter.hasConnectedApps()) {\n await appRouter.waitForApp(undefined, timeout);\n }\n\n const apps = appRouter.getApps();\n const appsWithWindows = await Promise.all(apps.map((app) => appWithWindows(appRouter, app)));\n\n return textContent(JSON.stringify(appsWithWindows, null, 2));\n },\n });\n\nconst screenshotResult = (\n result: { data: string; mimeType: string; savedPath?: string },\n shouldReturnImage: boolean,\n): CallToolResult => {\n if (result.savedPath === undefined) {\n return shouldReturnImage\n ? imageContent(result.data, result.mimeType)\n : textError(\n \"Nothing to return: `returnImage` was false and no `path` was given, so the screenshot was \" +\n \"neither saved nor returned. Pass `path` to save it, or leave `returnImage` unset.\",\n );\n }\n\n const saved = { type: \"text\", text: `Screenshot saved to ${result.savedPath}` } as const;\n\n if (!shouldReturnImage) {\n return { content: [saved] };\n }\n\n return { content: [saved, { type: \"image\", data: result.data, mimeType: result.mimeType }] };\n};\n\nconst screenshotTool = (appRouter: AppRouter): Tool =>\n defineTool({\n name: \"gtkx_take_screenshot\",\n title: \"Take screenshot\",\n kind: \"readOnly\",\n description:\n \"Capture a screenshot of a window. Returns base64-encoded PNG image data, and optionally writes \" +\n \"the PNG to `path` on the app's machine. You can't target widgets from a screenshot; use \" +\n \"`gtkx_get_widget_tree` to find widget IDs for interaction.\",\n inputSchema: screenshotShape,\n handler: async ({ applicationId, appTimeout, returnImage, ...params }) => {\n const result = await appRouter.sendToApp<{ data: string; mimeType: string; savedPath?: string }>(\n applicationId,\n \"widget.screenshot\",\n params,\n appTimeout,\n );\n\n return screenshotResult(result, returnImage !== false);\n },\n });\n\nconst widgetPropsTool = (appRouter: AppRouter): Tool =>\n defineTool({\n name: \"gtkx_get_widget_props\",\n title: \"Get widget properties\",\n kind: \"readOnly\",\n description:\n \"Get a fixed summary of one widget by ID: type, accessible role, name, text, sensitivity, \" +\n \"visibility, CSS classes, and the same summary for its descendants. The subtree is bounded \" +\n `twice: ${String(DEFAULT_SUBTREE_DEPTH)} levels deep unless \\`maxDepth\\` says otherwise, and ` +\n `${String(MAX_SUBTREE_WIDGETS)} widgets in all, filled breadth first. Wherever either bound ` +\n \"cut a branch, that widget carries `hiddenChildren`, the count of its own direct children left \" +\n \"out rather than of everything below them; call again with that widget's ID to drill in, or \" +\n \"use `gtkx_get_widget_tree` for a wider map. Pass `properties` to read GObject properties too; \" +\n \"they come back first in the payload, each under its canonical kebab-case name as \" +\n \"`{type, value}`, where an enum or flags value is its GType value name, a 64-bit integer a \" +\n \"decimal string, and an object its GType name plus `widgetId` when it is a widget. Asking for \" +\n \"a property the widget does not have fails; a value that cannot be marshalled carries a `note` \" +\n \"instead.\",\n inputSchema: widgetPropsShape,\n handler: async ({ applicationId, appTimeout, ...params }) => {\n const result = await appRouter.sendToApp(applicationId, \"widget.getProps\", params, appTimeout);\n\n return textContent(JSON.stringify(result, null, 2));\n },\n });\n\nfunction buildInspectionTools(appRouter: AppRouter): Tool[] {\n return [\n listAppsTool(appRouter),\n defineTool({\n name: \"gtkx_get_widget_tree\",\n title: \"Widget tree\",\n kind: \"readOnly\",\n description:\n \"Get the widget hierarchy for a connected GTKX app. Returns a tree of widgets with their IDs, \" +\n \"types, roles, and properties. For large apps, pass `maxDepth` for a shallow overview and/or \" +\n \"`rootId` to render just one subtree instead of the whole (possibly truncated) tree.\",\n inputSchema: treeShape,\n handler: async ({ applicationId, appTimeout, rootId, maxDepth }) => {\n const result = await appRouter.sendToApp<{ tree: string }>(applicationId, \"widget.getTree\", {\n rootId,\n maxDepth,\n }, appTimeout);\n\n return textContent(result.tree);\n },\n }),\n defineTool({\n name: \"gtkx_query_widgets\",\n title: \"Query widgets\",\n kind: \"readOnly\",\n description:\n \"Find widgets by role, text, name, or label. Returns each match with its ID and the same \" +\n \"fixed summary `gtkx_get_widget_props` returns, with no descendants: a match that has \" +\n \"children carries `hiddenChildren`, the count of its direct children left out. Read a \" +\n \"match's subtree with `gtkx_get_widget_props` or `gtkx_get_widget_tree`.\",\n inputSchema: queryWidgetsShape,\n handler: async ({ applicationId, appTimeout, ...params }) => {\n const result = await appRouter.sendToApp(applicationId, \"widget.query\", params, appTimeout);\n\n return textContent(JSON.stringify(result, null, 2));\n },\n }),\n widgetPropsTool(appRouter),\n screenshotTool(appRouter),\n ];\n}\n\nfunction buildInteractionTools(appRouter: AppRouter): Tool[] {\n return [\n defineTool({\n name: \"gtkx_click\",\n title: \"Click widget\",\n kind: \"action\",\n description:\n \"Click a widget through userEvent.click, with no special case per widget. Works with \" +\n \"buttons, checkboxes, switches, list and grid rows, tree expanders, and column headers: a \" +\n \"row is selected, an expander toggles its row's expansion, and a header sorts its column.\",\n inputSchema: widgetIdShape,\n handler: async ({ applicationId, appTimeout, ...params }) => {\n await appRouter.sendToApp(applicationId, \"widget.click\", params, appTimeout);\n\n return textContent(\"Clicked\");\n },\n }),\n defineTool({\n name: \"gtkx_type\",\n title: \"Type text\",\n kind: \"action\",\n description: \"Type text into an editable widget like Entry or TextView\",\n inputSchema: typeShape,\n handler: async ({ applicationId, appTimeout, ...params }) => {\n await appRouter.sendToApp(applicationId, \"widget.type\", params, appTimeout);\n\n return textContent(\"Typed text\");\n },\n }),\n defineTool({\n name: \"gtkx_fire_event\",\n title: \"Fire event\",\n kind: \"action\",\n description: \"Emit a GTK4 signal on a widget. Use this for custom interactions.\",\n inputSchema: fireEventShape,\n handler: async ({ applicationId, appTimeout, ...params }) => {\n const result = await appRouter.sendToApp(applicationId, \"widget.fireEvent\", params, appTimeout);\n\n return textContent(JSON.stringify(result, null, 2));\n },\n }),\n ];\n}\n\nfunction buildTools(appRouter: AppRouter): Tool[] {\n return [...buildInspectionTools(appRouter), ...buildInteractionTools(appRouter)];\n}\n\nconst registerTools = (\n mcpServer: McpServer,\n appRouter: AppRouter,\n provider: ReferenceProvider,\n settings: McpSettings,\n): void => {\n const tools = selectTools([...buildTools(appRouter), ...buildReferenceTools(provider)], settings);\n\n if (tools.length === 0) {\n log.warn(\"no tools matched the configured filter; the server is registering none\");\n }\n\n for (const tool of tools) {\n registerTool(mcpServer, tool);\n }\n};\n\nconst stoppedServerError = (): Error => new Error(\"createMcpServer: a stopped server cannot be started again\");\n\nconst wasStopRequested = (state: ServerLifecycle): boolean => state.isStopRequested;\n\nfunction stopServer(state: ServerLifecycle): Promise<void> {\n if (state.shutdown !== null) {\n return state.shutdown;\n }\n\n state.isStopRequested = true;\n state.appRouter.dispose();\n const startup = state.startup;\n const shutdown = (async (): Promise<void> => {\n if (startup !== null) {\n await Promise.allSettled([startup]);\n }\n\n await state.socketServer.stop();\n await state.mcpServer.close();\n })();\n\n state.shutdown = shutdown;\n\n return shutdown;\n}\n\nfunction startServer(state: ServerLifecycle): Promise<void> {\n if (wasStopRequested(state)) {\n return Promise.reject(stoppedServerError());\n }\n\n if (state.startup !== null) {\n return state.startup;\n }\n\n const startup = (async (): Promise<void> => {\n try {\n await state.socketServer.start();\n\n if (wasStopRequested(state)) {\n return;\n }\n\n log.info(`socket server listening on ${state.socketPath}`);\n await connectStdio(state.mcpServer, () => stopServer(state));\n } catch (error) {\n if (!wasStopRequested(state)) {\n state.isStopRequested = true;\n state.appRouter.dispose();\n await state.socketServer.stop();\n await state.mcpServer.close();\n }\n\n throw error;\n }\n })();\n\n state.startup = startup;\n\n return startup;\n}\n\nconst createServerHandle = (\n socketServer: SocketServer,\n mcpServer: McpServer,\n appRouter: AppRouter,\n socketPath: string,\n): McpServerHandle => {\n const state: ServerLifecycle = {\n socketServer,\n mcpServer,\n appRouter,\n socketPath,\n isStopRequested: false,\n startup: null,\n shutdown: null,\n };\n\n return { start: () => startServer(state), stop: () => stopServer(state) };\n};\n\nconst createMcpServer = (options: CreateMcpServerOptions): McpServerHandle => {\n const socketAddress = resolveMcpSocketAddress(options.socketPath);\n const socketPath = socketAddress.path;\n\n if (socketAddress.fallbackDirectory !== null) {\n log.warn(`MCP socket path exceeds the safe Unix byte budget; using private fallback ${socketPath}`);\n }\n\n const registry = new ConnectionRegistry();\n const socketServer = new SocketServer(registry, socketAddress);\n const appRouter = new AppRouter(registry);\n registry.addEventListener(\"error\", logSocketError);\n\n appRouter.addEventListener(\"appRegistered\", (event) => {\n const appInfo = (event as AppRegisteredEvent).detail;\n log.info(`app registered: ${appInfo.applicationId} (PID: ${String(appInfo.pid)})`);\n });\n\n appRouter.addEventListener(\"appUnregistered\", (event) => {\n log.info(`app unregistered: ${(event as AppUnregisteredEvent).detail}`);\n });\n\n const mcpServer = new McpServer({ name: \"gtkx-mcp\", version: options.version }, { instructions: INSTRUCTIONS });\n const referenceProvider = createReferenceProvider({ getAppRoot: () => appRouter.getProjectRoot() });\n registerTools(mcpServer, appRouter, referenceProvider, options.settings ?? DEFAULT_SETTINGS);\n registerReferenceResources(mcpServer, referenceProvider);\n\n return createServerHandle(socketServer, mcpServer, appRouter, socketPath);\n};\n\nconst configuredSettings = async (cwd: string): Promise<McpSettings> => {\n try {\n const { config } = await loadConfig(cwd);\n\n return resolveMcpSettings(config);\n } catch {\n return DEFAULT_SETTINGS;\n }\n};\n\nconst resolveSettings = async (options: ServerOptions): Promise<McpSettings> => {\n const configured = await configuredSettings(options.cwd ?? process.cwd());\n\n return {\n tools: options.tools ?? configured.tools,\n isReadOnly: options.isReadOnly ?? configured.isReadOnly,\n };\n};\n\nconst splitPatterns = (values: string[]): string[] =>\n values.flatMap((value) => value.split(\",\")).map((value) => value.trim()).filter((value) => value.length > 0);\n\nconst parseServerArgs = (argv: string[]): ServerOptions => {\n const { values } = parseArgs({\n args: argv,\n options: {\n tools: { type: \"string\", multiple: true },\n \"read-only\": { type: \"boolean\" },\n },\n allowPositionals: false,\n });\n\n const tools = values.tools === undefined ? undefined : splitPatterns(values.tools);\n\n return {\n ...(tools !== undefined && { tools }),\n ...(values[\"read-only\"] !== undefined && { isReadOnly: values[\"read-only\"] }),\n };\n};\n\nasync function main(options: ServerOptions = {}): Promise<void> {\n const settings = await resolveSettings(options);\n const server = createMcpServer({ version, settings });\n\n installGracefulShutdown({\n onSignal: () => server.stop(),\n });\n\n await server.start();\n}\n\nexport { log, main, main as runMcpServer, parseServerArgs };\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
type McpSocketAddress = {
|
|
2
|
+
path: string;
|
|
3
|
+
fallbackDirectory: string | null;
|
|
4
|
+
};
|
|
5
|
+
declare const MCP_SOCKET_PATH_ENV = "GTKX_MCP_SOCKET_PATH";
|
|
6
|
+
declare const resolveMcpSocketAddress: (providedPath?: string) => McpSocketAddress;
|
|
7
|
+
declare const resolveMcpSocketPath: (providedPath?: string) => string;
|
|
8
|
+
declare const prepareMcpSocketAddress: (address: McpSocketAddress) => void;
|
|
9
|
+
declare const cleanupMcpSocketAddress: (address: McpSocketAddress) => void;
|
|
10
|
+
export { cleanupMcpSocketAddress, MCP_SOCKET_PATH_ENV, prepareMcpSocketAddress, resolveMcpSocketAddress, resolveMcpSocketPath, type McpSocketAddress, };
|
|
11
|
+
//# sourceMappingURL=socket-path.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket-path.d.ts","sourceRoot":"","sources":["../src/socket-path.ts"],"names":[],"mappings":"AAKA,KAAK,gBAAgB,GAAG;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,iBAAiB,EAAE,MAAM,GAAG,IAAI,CAAC;CACpC,CAAC;AAEF,QAAA,MAAM,mBAAmB,yBAAyB,CAAC;AAsDnD,QAAA,MAAM,uBAAuB,GAAI,eAAe,MAAM,KAAG,gBAMxD,CAAC;AAEF,QAAA,MAAM,oBAAoB,GAAI,eAAe,MAAM,KAAG,MAAoD,CAAC;AAE3G,QAAA,MAAM,uBAAuB,GAAI,SAAS,gBAAgB,KAAG,IAI5D,CAAC;AAEF,QAAA,MAAM,uBAAuB,GAAI,SAAS,gBAAgB,KAAG,IAa5D,CAAC;AAEF,OAAO,EACH,uBAAuB,EACvB,mBAAmB,EACnB,uBAAuB,EACvB,uBAAuB,EACvB,oBAAoB,EACpB,KAAK,gBAAgB,GACxB,CAAC"}
|