@j0hanz/filesystem-mcp 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -27
- package/dist/cli-help.d.ts.map +1 -1
- package/dist/cli-help.js +10 -2
- package/dist/cli-help.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +10 -5
- package/dist/cli.js.map +1 -1
- package/dist/core/concurrency.d.ts.map +1 -1
- package/dist/core/concurrency.js +21 -6
- package/dist/core/concurrency.js.map +1 -1
- package/dist/core/config.d.ts +2 -0
- package/dist/core/config.d.ts.map +1 -1
- package/dist/core/config.js.map +1 -1
- package/dist/core/errors.d.ts +6 -9
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +58 -102
- package/dist/core/errors.js.map +1 -1
- package/dist/core/file-uri.d.ts +5 -1
- package/dist/core/file-uri.d.ts.map +1 -1
- package/dist/core/file-uri.js +6 -2
- package/dist/core/file-uri.js.map +1 -1
- package/dist/core/fmt.d.ts +0 -1
- package/dist/core/fmt.d.ts.map +1 -1
- package/dist/core/fmt.js +0 -1
- package/dist/core/fmt.js.map +1 -1
- package/dist/core/fs.d.ts +31 -1
- package/dist/core/fs.d.ts.map +1 -1
- package/dist/core/fs.js +142 -2
- package/dist/core/fs.js.map +1 -1
- package/dist/core/glob.d.ts.map +1 -1
- package/dist/core/glob.js +3 -8
- package/dist/core/glob.js.map +1 -1
- package/dist/core/input-required.d.ts +8 -17
- package/dist/core/input-required.d.ts.map +1 -1
- package/dist/core/input-required.js +32 -47
- package/dist/core/input-required.js.map +1 -1
- package/dist/core/observability.d.ts +9 -0
- package/dist/core/observability.d.ts.map +1 -1
- package/dist/core/observability.js +11 -0
- package/dist/core/observability.js.map +1 -1
- package/dist/core/page-store.d.ts +4 -3
- package/dist/core/page-store.d.ts.map +1 -1
- package/dist/core/page-store.js +4 -3
- package/dist/core/page-store.js.map +1 -1
- package/dist/core/search.d.ts +5 -0
- package/dist/core/search.d.ts.map +1 -1
- package/dist/core/search.js +18 -19
- package/dist/core/search.js.map +1 -1
- package/dist/core/sensitive.d.ts +4 -2
- package/dist/core/sensitive.d.ts.map +1 -1
- package/dist/core/sensitive.js +261 -43
- package/dist/core/sensitive.js.map +1 -1
- package/dist/core/watcher-registry.d.ts.map +1 -1
- package/dist/core/watcher-registry.js +5 -1
- package/dist/core/watcher-registry.js.map +1 -1
- package/dist/resources.d.ts.map +1 -1
- package/dist/resources.js +13 -4
- package/dist/resources.js.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +7 -2
- package/dist/server.js.map +1 -1
- package/dist/tools/create.d.ts.map +1 -1
- package/dist/tools/create.js +163 -14
- package/dist/tools/create.js.map +1 -1
- package/dist/tools/define.d.ts +6 -1
- package/dist/tools/define.d.ts.map +1 -1
- package/dist/tools/define.js +25 -5
- package/dist/tools/define.js.map +1 -1
- package/dist/tools/delete.d.ts.map +1 -1
- package/dist/tools/delete.js +8 -11
- package/dist/tools/delete.js.map +1 -1
- package/dist/tools/edit.d.ts.map +1 -1
- package/dist/tools/edit.js +77 -69
- package/dist/tools/edit.js.map +1 -1
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +1 -0
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/move.d.ts.map +1 -1
- package/dist/tools/move.js +14 -33
- package/dist/tools/move.js.map +1 -1
- package/dist/tools/patch.js +3 -3
- package/dist/tools/patch.js.map +1 -1
- package/dist/tools/search-text.d.ts.map +1 -1
- package/dist/tools/search-text.js +64 -1
- package/dist/tools/search-text.js.map +1 -1
- package/dist/transport/http.d.ts.map +1 -1
- package/dist/transport/http.js +5 -1
- package/dist/transport/http.js.map +1 -1
- package/dist/transport/stdio.d.ts +1 -0
- package/dist/transport/stdio.d.ts.map +1 -1
- package/dist/transport/stdio.js +1 -0
- package/dist/transport/stdio.js.map +1 -1
- package/package.json +6 -9
package/dist/resources.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resources.js","sourceRoot":"","sources":["../src/resources.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,oBAAoB,EACpB,aAAa,EACb,iBAAiB,EACjB,qBAAqB,EACrB,gBAAgB,EAChB,wBAAwB,GACzB,MAAM,8BAA8B,CAAC;AAGtC,OAAO,EACL,SAAS,EACT,yBAAyB,EACzB,WAAW,EACX,aAAa,EACb,SAAS,GACV,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,WAAW,EACX,4BAA4B,GAC7B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAGzD,OAAO,EACL,qBAAqB,EACrB,YAAY,GAEb,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,mBAAmB,EACnB,oBAAoB,EACpB,gBAAgB,EAChB,cAAc,GACf,MAAM,mBAAmB,CAAC;AAoC3B;;;;;;GAMG;AACH,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,CACL,SAAS,CAAC,KAAK,CAAC;QAChB,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,SAAS,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,aAAa,CAAC,CAC/E,CAAC;AACJ,CAAC;AAgDD,kEAAkE;AAClE,eAAe;AACf,kEAAkE;AAElE,SAAS,0BAA0B,CAAC,OAAoC;IACtE,MAAM,IAAI,GAAG,cAAc,CAAC,mBAAmB,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;IACnE,OAAO;QACL,IAAI,EAAE,6BAA6B;QACnC,KAAK,EAAE,qBAAqB;QAC5B,WAAW,EAAE,oBAAoB;QACjC,QAAQ,EAAE,eAAe;QACzB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,SAAS;gBACpC,MAAM,UAAU,GAAG,QAAQ,CAAC,GAAG,IAAI,QAAQ,CAAC,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;gBACtE,IAAI,CAAC,UAAU;oBAAE,SAAS;gBAC1B,IAAI,oBAAoB,CAAC,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,UAAU,EAAE,CAAC,EAAE,CAAC;oBAChF,QAAQ,CAAC,WAAW,CAAC,iBAAiB,CAAC,QAAQ,EAAE,CAAC,CAAC;gBACrD,CAAC;YACH,CAAC;YACD,OAAO,EAAE,CAAC;QACZ,CAAC,CACF,CAAC;IACJ,CAAC;IAED,OAAO;QACL,OAAO;YACL,KAAK,MAAM,QAAQ,IAAI,iBAAiB,EAAE,CAAC;gBACzC,IAAI,QAAQ,CAAC,OAAO,EAAE,CAAC;oBACrB,QAAQ,CAAC,OAAO,EAAE,CAAC;gBACrB,CAAC;YACH,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n CacheHint,\n CompleteResourceTemplateCallback,\n McpServer,\n ReadResourceResult,\n Resource,\n ResourceUpdatedNotificationParams,\n Role,\n ServerContext,\n ServerNotifier,\n SubscribeRequestParams,\n UnsubscribeRequestParams,\n} from '@modelcontextprotocol/server';\nimport {\n checkResourceAllowed,\n ProtocolError,\n ProtocolErrorCode,\n ResourceNotFoundError,\n ResourceTemplate,\n resourceUrlFromServerUrl,\n} from '@modelcontextprotocol/server';\n\nimport type { FsError } from './core/errors.js';\nimport {\n ErrorCode,\n formatUnknownErrorMessage,\n fsErrorCode,\n hasErrorShape,\n isFsError,\n} from './core/errors.js';\nimport {\n decodeFileUriPath,\n encodeFileUriPath,\n extractPath,\n FILESYSTEM_FILE_URI_TEMPLATE,\n} from './core/file-uri.js';\nimport { GuardedFileSystem } from './core/fs.js';\nimport { Logger } from './core/observability.js';\nimport { PathCompleter } from './core/path-completer.js';\nimport type { PathGuard } from './core/path.js';\nimport type { ResourceStore } from './core/store.js';\nimport {\n createWatcherRegistry,\n MAX_WATCHERS,\n type WatcherRegistry,\n} from './core/watcher-registry.js';\nimport {\n buildSectionsRecord,\n INSTRUCTIONS_SUMMARY,\n INSTRUCTIONS_URI,\n renderSections,\n} from './instructions.js';\n\n// ═══════════════════════════════════════════════════════════════\n// shared\n// ═══════════════════════════════════════════════════════════════\n\nexport interface ResourceRegistrationOptions {\n resourceStore: ResourceStore;\n pathGuard: PathGuard;\n /** Mirrors the `--read-only` gate so the instructions match the tools actually registered. */\n readOnly: boolean;\n /**\n * Shared file-watcher registry for the modern (per-request) HTTP leg. When set,\n * the resource uses this handler-scoped registry instead of creating its own\n * per-server one, so file-change watchers persist across requests and publish\n * to the shared ServerEventBus. Omitted (per-server registry) on legacy/stdio.\n */\n watcherRegistry?: WatcherRegistry;\n /** Modern-leg typed notification publisher. */\n notifier?: ServerNotifier;\n /** The protocol era this instance serves; omitted where the caller does not know. */\n era?: 'legacy' | 'modern';\n /**\n * Scope for shared-content cache hints. 'private' when the endpoint is\n * API-key gated, mirroring the list hints in server.ts — a shared cache must\n * not store an authenticated response body. Defaults to 'public'.\n */\n cacheScope?: 'public' | 'private';\n}\n\ntype ResourceRegistrarDeps = Omit<ResourceRegistrationOptions, 'pathGuard' | 'readOnly'> & {\n readonly server: McpServer;\n readonly pathGuard: PathGuard;\n readonly readOnly?: boolean;\n};\n\n/**\n * A filesystem failure that reads as not-found on the resource wire, for both\n * `resources/read` and `resources/subscribe`. ACCESS_DENIED folds in\n * deliberately: masking whether an out-of-root or denylisted path exists is the\n * security-correct answer, and the `FsError` message still carries the real\n * cause to the client.\n */\nfunction isNotFoundish(error: unknown): error is FsError {\n return (\n isFsError(error) &&\n (error.code === ErrorCode.NOT_FOUND || error.code === ErrorCode.ACCESS_DENIED)\n );\n}\n\n// ═══════════════════════════════════════════════════════════════\n// contract\n// ═══════════════════════════════════════════════════════════════\n\ninterface BaseResourceContract {\n name: string;\n title?: string;\n description?: string;\n mimeType?: string;\n cacheHint?: CacheHint;\n annotations?: {\n audience?: Role[];\n priority?: number;\n };\n readonly read: (\n uri: URL,\n variables: Record<string, string | string[]>,\n ctx: ServerContext,\n ) => Promise<ReadResourceResult> | ReadResourceResult;\n readonly subscribe?: (\n uri: string,\n notify: (uri: string) => void,\n ) => Promise<boolean | undefined> | boolean | undefined;\n readonly unsubscribe?: (uri: string) => void;\n readonly destroy?: () => void;\n readonly list?: (\n ctx: ServerContext,\n ) => Promise<{ resources: Resource[] }> | { resources: Resource[] };\n}\n\n/** A resource with a fixed, enumerable URI (e.g. internal://instructions). */\ninterface StaticResourceContract extends BaseResourceContract {\n uri: string;\n uriTemplate?: never;\n complete?: never;\n}\n\n/** A resource identified by a URI template (FILESYSTEM_FILE_URI_TEMPLATE). */\ninterface TemplateResourceContract extends BaseResourceContract {\n uriTemplate: string;\n uri?: never;\n complete?: { path: CompleteResourceTemplateCallback };\n}\n\ntype ResourceContract = StaticResourceContract | TemplateResourceContract;\n\n// ═══════════════════════════════════════════════════════════════\n// instructions\n// ═══════════════════════════════════════════════════════════════\n\nfunction createInstructionsResource(options: ResourceRegistrationOptions): ResourceContract {\n const text = renderSections(buildSectionsRecord(options.readOnly));\n return {\n name: 'filesystem-mcp-instructions',\n title: 'Server Instructions',\n description: INSTRUCTIONS_SUMMARY,\n mimeType: 'text/markdown',\n uri: INSTRUCTIONS_URI,\n annotations: { audience: ['assistant'], priority: 0.8 },\n cacheHint: { cacheScope: options.cacheScope ?? 'public', ttlMs: 300_000 },\n read(uri) {\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'text/markdown',\n text,\n },\n ],\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════\n// filesystem\n// ═══════════════════════════════════════════════════════════════\n\nfunction createFilesystemResource(options: ResourceRegistrationOptions): ResourceContract {\n const completer = new PathCompleter(options.pathGuard);\n const registry = options.watcherRegistry ?? createWatcherRegistry();\n // Only the per-server (legacy/stdio) registry is owned by this resource and\n // destroyed on dispose; the shared modern-leg registry is owned by the host\n // and torn down at server shutdown.\n const ownsRegistry = options.watcherRegistry === undefined;\n // The URIs this connection holds a `resources/subscribe` lease for. The wire\n // verb is per-URI and idempotent — a second subscribe is the same\n // subscription, and one unsubscribe ends it — but the registry ref-counts\n // leases (the HTTP listen leg needs that). Without this set a double\n // subscribe took two leases that one unsubscribe could not release, and an\n // unsubscribe for a URI never subscribed released a lease this connection\n // never took, dropping a watcher some other holder still wanted.\n const leasedUris = new Set<string>();\n // Subscribes mid-acquire, keyed by URI. Two concurrent subscribes for the\n // same URI must share one acquire: both passing the `leasedUris` check\n // before either finished took two registry leases that the single set entry\n // could release only once — on the shared modern registry that orphan lease\n // pinned a watcher until process shutdown.\n const inflight = new Map<string, Promise<boolean | undefined>>();\n\n return {\n name: 'filesystem-mcp-file',\n title: 'Workspace File',\n description: 'Read a file from the workspace. Subscribe to get updates when the file changes.',\n uriTemplate: FILESYSTEM_FILE_URI_TEMPLATE,\n annotations: { audience: ['assistant'], priority: 0.8 },\n // Without this the SDK falls back to its conservative `{ ttlMs: 0,\n // cacheScope: 'private' }`, making every file read uncacheable — and this\n // is the one resource with a live invalidation channel, so TTL and the\n // watcher compose exactly as the spec's caching section describes. The TTL\n // stays short because a non-subscriber gets no invalidation signal at all.\n cacheHint: { cacheScope: options.cacheScope ?? 'public', ttlMs: 5_000 },\n\n // No `list`: the template registers with `list: undefined` — readable but\n // not enumerable. Listing each allowed root as a concrete resource\n // duplicated the template and grew resources/list linearly with roots;\n // `list_roots` owns root discovery.\n\n async read(uri, _variables, _ctx: ServerContext) {\n // Decode via extractPath — the same decoder resources/subscribe uses — so\n // both consumers are symmetric with buildFileResourceUri's encoding. The\n // {+path} template variable arrives still percent-encoded, so validating\n // it directly would treat \"c%3A/proj/a.ts\" as a literal relative path;\n // no fallback to it here, or the two branches would validate different\n // strings. extractPath only fails past the template match on undecodable\n // percent-encoding, which is the caller's malformed URI.\n const rawPath = extractPath(uri.href);\n if (rawPath === undefined) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n 'Malformed file URI: path is not valid percent-encoding',\n );\n }\n await options.pathGuard.validateExistingPath(rawPath);\n const fs = new GuardedFileSystem(options.pathGuard);\n const readResult = await fs.readRaw(rawPath);\n\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: readResult.mimeType || 'application/octet-stream',\n ...(readResult.isBinary\n ? { blob: readResult.content.toString('base64') }\n : { text: readResult.content.toString('utf-8') }),\n },\n ],\n };\n },\n\n complete: {\n // Both ends speak the `{+path}` form (see encodeFileUriPath), not raw OS\n // paths: the partial arriving here is whatever this returned last, so the\n // decode mirrors the encode. An undecodable partial is matched as typed.\n path: async (value) => {\n const suggestions = await completer.suggest(decodeFileUriPath(value) ?? value);\n return suggestions.map(encodeFileUriPath);\n },\n },\n\n subscribe(uri, notify) {\n // Already subscribed on this connection: the watcher is live and the sink\n // is registered, so this is a no-op success rather than a second lease.\n if (leasedUris.has(uri)) return undefined;\n // A subscribe for this URI is mid-acquire: share its outcome instead of\n // taking a second lease the lease set cannot represent.\n const pending = inflight.get(uri);\n if (pending) return pending;\n\n const acquire = async (): Promise<boolean | undefined> => {\n const result = await registry.acquire(options.pathGuard, uri, notify, {\n markSubscribe: true,\n });\n if (result.ok) {\n leasedUris.add(uri);\n return undefined;\n }\n\n if (result.reason === 'bad-uri') {\n throw new ResourceNotFoundError(uri, `Cannot subscribe: not a filesystem URI`);\n }\n if (result.reason === 'invalid-path') {\n const err = result.error;\n if (isNotFoundish(err)) {\n throw new ResourceNotFoundError(uri, `Cannot subscribe to ${uri}: ${err.message}`);\n }\n Logger.warn(\n `Unexpected error validating path for watcher ${uri}: ${formatUnknownErrorMessage(err)}`,\n );\n throw err;\n }\n // Unsubscribed (or the registry destroyed) mid-await: the caller already\n // asked for this to stop, so there is nothing to reject.\n if (result.reason === 'stale') return undefined;\n // capped / attach-failed: `false` tells the handler to reject, since\n // undefined would report success with no watcher attached.\n return false;\n };\n\n const promise = acquire().finally(() => inflight.delete(uri));\n inflight.set(uri, promise);\n return promise;\n },\n\n unsubscribe(uri) {\n // Only release a lease this connection actually took.\n if (!leasedUris.delete(uri)) return;\n registry.release(uri);\n },\n\n destroy() {\n // Release what this connection still holds before the registry goes: on\n // the shared (modern) registry nothing else would ever end these leases.\n for (const uri of leasedUris) registry.release(uri);\n leasedUris.clear();\n if (ownsRegistry) registry.destroy();\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════\n// result\n// ═══════════════════════════════════════════════════════════════\n\nfunction createResultResource(options: ResourceRegistrationOptions): ResourceContract {\n return {\n name: 'filesystem-mcp-result',\n title: 'Cached Tool Result',\n description:\n 'Ephemeral cached tool output. Listed via resources/list; entries expire after the cache TTL.',\n mimeType: 'application/json',\n uriTemplate: 'filesystem-mcp://result/{id}',\n annotations: { audience: ['assistant'], priority: 0.3 },\n cacheHint: { cacheScope: 'private', ttlMs: 60_000 },\n list() {\n const store = options.resourceStore;\n const uris = store.keys(); // prunes expired first\n const resources: Resource[] = [];\n for (const uri of uris) {\n try {\n const entry = store.getEntry(uri);\n resources.push({\n uri: entry.uri,\n name: entry.name,\n mimeType: entry.mimeType,\n size: entry.size,\n });\n } catch (err) {\n // An entry may expire between keys() and getEntry; skip it.\n if (isFsError(err) && err.code === ErrorCode.NOT_FOUND) continue;\n throw err;\n }\n }\n // Recent-first: keys() returns insertion order, so the newest is last.\n resources.reverse();\n return { resources };\n },\n read(uri, variables) {\n const { id } = variables;\n if (typeof id !== 'string' || id.length === 0) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n 'Malformed result URI: missing {id}. Use the exact resourceUri returned by the tool.',\n );\n }\n\n let entry;\n try {\n entry = options.resourceStore.getEntry(uri.toString());\n } catch (err) {\n if (isFsError(err) && err.code === ErrorCode.NOT_FOUND) {\n throw new ResourceNotFoundError(\n uri.toString(),\n 'Cached result not found or expired. Re-run the tool to regenerate.',\n );\n }\n throw err;\n }\n return {\n contents: [{ uri: entry.uri, mimeType: entry.mimeType, text: entry.text }],\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════\n// export contracts\n// ═══════════════════════════════════════════════════════════════\n\nexport function getResourceContracts(options: ResourceRegistrationOptions): ResourceContract[] {\n return [\n createInstructionsResource(options),\n createResultResource(options),\n createFilesystemResource(options),\n ];\n}\n\n// ═══════════════════════════════════════════════════════════════\n// registrar\n// ═══════════════════════════════════════════════════════════════\n\nfunction wrapRead(contract: ResourceContract) {\n return async (uri: URL, variables: Record<string, string | string[]>, ctx: ServerContext) => {\n try {\n return await contract.read(uri, variables, ctx);\n } catch (error) {\n if (hasErrorShape(error, 'ProtocolError')) throw error;\n // A missing or out-of-root path is a not-found, not a malformed request.\n // The SDK puts ResourceNotFoundError on the wire as -32602 with\n // `data.uri`, which is what clients match on; -32002 is the older code\n // they also accept, and this SDK never emits it.\n if (isNotFoundish(error)) {\n throw new ResourceNotFoundError(uri.toString(), error.message);\n }\n // A remaining FsError (NOT_FILE, TOO_LARGE, ...) traces to the\n // caller-supplied URI; anything else is a server-side failure and must\n // not be blamed on the request.\n const msg = isFsError(error) ? error.message : formatUnknownErrorMessage(error);\n throw new ProtocolError(fsErrorCode(error), msg);\n }\n };\n}\n\nexport function registerResources(deps: ResourceRegistrarDeps): { dispose(): void } {\n const server = deps.server;\n const resourceContracts = getResourceContracts({ ...deps, readOnly: deps.readOnly ?? false });\n\n for (const contract of resourceContracts) {\n const config = {\n ...(contract.title !== undefined ? { title: contract.title } : {}),\n ...(contract.description !== undefined ? { description: contract.description } : {}),\n ...(contract.mimeType !== undefined ? { mimeType: contract.mimeType } : {}),\n ...(contract.annotations !== undefined ? { annotations: contract.annotations } : {}),\n ...(contract.cacheHint !== undefined ? { cacheHint: contract.cacheHint } : {}),\n };\n\n if (contract.uriTemplate) {\n const template = new ResourceTemplate(contract.uriTemplate, {\n list: contract.list,\n ...(contract.complete ? { complete: contract.complete } : {}),\n });\n\n server.registerResource(contract.name, template, config, wrapRead(contract));\n } else if (contract.uri) {\n server.registerResource(contract.name, contract.uri, config, (uri: URL, ctx: ServerContext) =>\n wrapRead(contract)(uri, {}, ctx),\n );\n }\n }\n\n // `resources/subscribe`/`unsubscribe` are 2025-era-only verbs; a modern\n // server answers `-32601 Method not found` for them, so registering these\n // handlers on a modern-era instance would dispatch to code no request can\n // reach.\n if (deps.era !== 'modern') {\n server.server.assertCanSetRequestHandler('resources/subscribe');\n server.server.assertCanSetRequestHandler('resources/unsubscribe');\n\n // One stable callback for the whole registrar, NOT one per subscribe. The\n // registry holds these in a Set keyed by identity, so a fresh closure per\n // request made a second `resources/subscribe` for the same URI register a\n // second sink: one file change then sent N notifications, and `unsubscribe`\n // (which only ends a lease) removed none of them. Subscribe is per-URI on\n // the wire, so the sink must be too — this makes it idempotent.\n const notifyUpdated = (updatedUri: string): void => {\n if (deps.notifier) {\n deps.notifier.resourceUpdated(updatedUri);\n return;\n }\n const updatePayload: ResourceUpdatedNotificationParams = { uri: updatedUri };\n // A failed notify means the connection went away; nothing to recover.\n void server.server.sendResourceUpdated(updatePayload).catch((err: unknown) => {\n Logger.debug('resource update not delivered', {\n uri: updatedUri,\n error: formatUnknownErrorMessage(err),\n });\n });\n };\n\n server.server.setRequestHandler(\n 'resources/subscribe',\n async (req: { params: SubscribeRequestParams }) => {\n const requestedResource = resourceUrlFromServerUrl(req.params.uri);\n let foundMatch = false;\n // A resource that exists but has no watcher (the instructions text, a\n // cached result) is NOT a not-found: reporting it as one told clients a\n // URI they can list and read does not exist. Track the two cases apart.\n let knownButNotSubscribable = false;\n for (const contract of resourceContracts) {\n const configured = contract.uri ?? contract.uriTemplate.split('{')[0];\n if (!contract.subscribe) {\n if (\n configured &&\n checkResourceAllowed({ requestedResource, configuredResource: configured })\n ) {\n knownButNotSubscribable = true;\n }\n continue;\n }\n if (!configured) continue;\n if (\n checkResourceAllowed({\n requestedResource,\n configuredResource: configured,\n })\n ) {\n foundMatch = true;\n const subscribeResult = await contract.subscribe(\n requestedResource.toString(),\n notifyUpdated,\n );\n if (subscribeResult === false) {\n // InternalError for want of anything better: ProtocolErrorCode\n // has no resource-limit member, and the message already names\n // the actionable cause.\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `Subscription rejected: no watcher attached (watcher limit ${MAX_WATCHERS} reached, or fs.watch failed to start).`,\n );\n }\n break;\n }\n }\n if (!foundMatch) {\n if (knownButNotSubscribable) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Resource ${requestedResource.toString()} does not support subscriptions; only ${FILESYSTEM_FILE_URI_TEMPLATE} does. Read it again for the current contents.`,\n );\n }\n throw new ResourceNotFoundError(\n requestedResource.toString(),\n `Resource not found: ${requestedResource.toString()}`,\n );\n }\n return {};\n },\n );\n\n server.server.setRequestHandler(\n 'resources/unsubscribe',\n (req: { params: UnsubscribeRequestParams }) => {\n // Route by URI prefix, mirroring the subscribe handler: a broadcast\n // to every contract works while only one is subscribable, but hands a\n // second subscribable contract someone else's URI the day it appears.\n const requestedResource = resourceUrlFromServerUrl(req.params.uri);\n for (const contract of resourceContracts) {\n if (!contract.unsubscribe) continue;\n const configured = contract.uri ?? contract.uriTemplate.split('{')[0];\n if (!configured) continue;\n if (checkResourceAllowed({ requestedResource, configuredResource: configured })) {\n contract.unsubscribe(requestedResource.toString());\n }\n }\n return {};\n },\n );\n }\n\n return {\n dispose(): void {\n for (const contract of resourceContracts) {\n if (contract.destroy) {\n contract.destroy();\n }\n }\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"resources.js","sourceRoot":"","sources":["../src/resources.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,oBAAoB,EACpB,aAAa,EACb,iBAAiB,EACjB,qBAAqB,EACrB,gBAAgB,EAChB,wBAAwB,GACzB,MAAM,8BAA8B,CAAC;AAGtC,OAAO,EAAE,SAAS,EAAE,yBAAyB,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAChG,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,WAAW,EACX,4BAA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,SAAS;gBAC1B,IAAI,oBAAoB,CAAC,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,UAAU,EAAE,CAAC,EAAE,CAAC;oBAChF,QAAQ,CAAC,WAAW,CAAC,iBAAiB,CAAC,QAAQ,EAAE,CAAC,CAAC;gBACrD,CAAC;YACH,CAAC;YACD,OAAO,EAAE,CAAC;QACZ,CAAC,CACF,CAAC;IACJ,CAAC;IAED,OAAO;QACL,OAAO;YACL,KAAK,MAAM,QAAQ,IAAI,iBAAiB,EAAE,CAAC;gBACzC,IAAI,QAAQ,CAAC,OAAO,EAAE,CAAC;oBACrB,QAAQ,CAAC,OAAO,EAAE,CAAC;gBACrB,CAAC;YACH,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n CacheHint,\n CompleteResourceTemplateCallback,\n McpServer,\n ReadResourceResult,\n Resource,\n ResourceUpdatedNotificationParams,\n Role,\n ServerContext,\n ServerNotifier,\n SubscribeRequestParams,\n UnsubscribeRequestParams,\n} from '@modelcontextprotocol/server';\nimport {\n checkResourceAllowed,\n ProtocolError,\n ProtocolErrorCode,\n ResourceNotFoundError,\n ResourceTemplate,\n resourceUrlFromServerUrl,\n} from '@modelcontextprotocol/server';\n\nimport type { FsError } from './core/errors.js';\nimport { ErrorCode, formatUnknownErrorMessage, fsErrorCode, isFsError } from './core/errors.js';\nimport {\n decodeFileUriPath,\n encodeFileUriPath,\n extractPath,\n FILESYSTEM_FILE_URI_TEMPLATE,\n} from './core/file-uri.js';\nimport { GuardedFileSystem } from './core/fs.js';\nimport { Logger } from './core/observability.js';\nimport { PathCompleter } from './core/path-completer.js';\nimport type { PathGuard } from './core/path.js';\nimport type { ResourceStore } from './core/store.js';\nimport {\n createWatcherRegistry,\n MAX_WATCHERS,\n type WatcherRegistry,\n} from './core/watcher-registry.js';\nimport {\n buildSectionsRecord,\n INSTRUCTIONS_SUMMARY,\n INSTRUCTIONS_URI,\n renderSections,\n} from './instructions.js';\n\n// ═══════════════════════════════════════════════════════════════\n// shared\n// ═══════════════════════════════════════════════════════════════\n\nexport interface ResourceRegistrationOptions {\n resourceStore: ResourceStore;\n pathGuard: PathGuard;\n /** Mirrors the `--read-only` gate so the instructions match the tools actually registered. */\n readOnly: boolean;\n /**\n * Shared file-watcher registry for the modern (per-request) HTTP leg. When set,\n * the resource uses this handler-scoped registry instead of creating its own\n * per-server one, so file-change watchers persist across requests and publish\n * to the shared ServerEventBus. Omitted (per-server registry) on legacy/stdio.\n */\n watcherRegistry?: WatcherRegistry;\n /** Modern-leg typed notification publisher. */\n notifier?: ServerNotifier;\n /** The protocol era this instance serves; omitted where the caller does not know. */\n era?: 'legacy' | 'modern';\n /**\n * Scope for shared-content cache hints. 'private' when the endpoint is\n * API-key gated, mirroring the list hints in server.ts — a shared cache must\n * not store an authenticated response body. Defaults to 'public'.\n */\n cacheScope?: 'public' | 'private';\n}\n\ntype ResourceRegistrarDeps = Omit<ResourceRegistrationOptions, 'pathGuard' | 'readOnly'> & {\n readonly server: McpServer;\n readonly pathGuard: PathGuard;\n readonly readOnly?: boolean;\n};\n\n/**\n * A filesystem failure that reads as not-found on the resource wire, for both\n * `resources/read` and `resources/subscribe`. ACCESS_DENIED folds in\n * deliberately: masking whether an out-of-root or denylisted path exists is the\n * security-correct answer, and the `FsError` message still carries the real\n * cause to the client.\n */\nfunction isNotFoundish(error: unknown): error is FsError {\n return (\n isFsError(error) &&\n (error.code === ErrorCode.NOT_FOUND || error.code === ErrorCode.ACCESS_DENIED)\n );\n}\n\n// ═══════════════════════════════════════════════════════════════\n// contract\n// ═══════════════════════════════════════════════════════════════\n\ninterface BaseResourceContract {\n name: string;\n title?: string;\n description?: string;\n mimeType?: string;\n cacheHint?: CacheHint;\n annotations?: {\n audience?: Role[];\n priority?: number;\n };\n readonly read: (\n uri: URL,\n variables: Record<string, string | string[]>,\n ctx: ServerContext,\n ) => Promise<ReadResourceResult> | ReadResourceResult;\n readonly subscribe?: (\n uri: string,\n notify: (uri: string) => void,\n ) => Promise<boolean | undefined> | boolean | undefined;\n readonly unsubscribe?: (uri: string) => void;\n readonly destroy?: () => void;\n readonly list?: (\n ctx: ServerContext,\n ) => Promise<{ resources: Resource[] }> | { resources: Resource[] };\n}\n\n/** A resource with a fixed, enumerable URI (e.g. internal://instructions). */\ninterface StaticResourceContract extends BaseResourceContract {\n uri: string;\n uriTemplate?: never;\n complete?: never;\n}\n\n/** A resource identified by a URI template (FILESYSTEM_FILE_URI_TEMPLATE). */\ninterface TemplateResourceContract extends BaseResourceContract {\n uriTemplate: string;\n uri?: never;\n complete?: { path: CompleteResourceTemplateCallback };\n}\n\ntype ResourceContract = StaticResourceContract | TemplateResourceContract;\n\n// ═══════════════════════════════════════════════════════════════\n// instructions\n// ═══════════════════════════════════════════════════════════════\n\nfunction createInstructionsResource(options: ResourceRegistrationOptions): ResourceContract {\n const text = renderSections(buildSectionsRecord(options.readOnly));\n return {\n name: 'filesystem-mcp-instructions',\n title: 'Server Instructions',\n description: INSTRUCTIONS_SUMMARY,\n mimeType: 'text/markdown',\n uri: INSTRUCTIONS_URI,\n annotations: { audience: ['assistant'], priority: 0.8 },\n cacheHint: { cacheScope: options.cacheScope ?? 'public', ttlMs: 300_000 },\n read(uri) {\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'text/markdown',\n text,\n },\n ],\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════\n// filesystem\n// ═══════════════════════════════════════════════════════════════\n\nfunction createFilesystemResource(options: ResourceRegistrationOptions): ResourceContract {\n const completer = new PathCompleter(options.pathGuard);\n const registry = options.watcherRegistry ?? createWatcherRegistry();\n // Only the per-server (legacy/stdio) registry is owned by this resource and\n // destroyed on dispose; the shared modern-leg registry is owned by the host\n // and torn down at server shutdown.\n const ownsRegistry = options.watcherRegistry === undefined;\n // The URIs this connection holds a `resources/subscribe` lease for. The wire\n // verb is per-URI and idempotent — a second subscribe is the same\n // subscription, and one unsubscribe ends it — but the registry ref-counts\n // leases (the HTTP listen leg needs that). Without this set a double\n // subscribe took two leases that one unsubscribe could not release, and an\n // unsubscribe for a URI never subscribed released a lease this connection\n // never took, dropping a watcher some other holder still wanted.\n const leasedUris = new Set<string>();\n // Subscribes mid-acquire, keyed by URI. Two concurrent subscribes for the\n // same URI must share one acquire: both passing the `leasedUris` check\n // before either finished took two registry leases that the single set entry\n // could release only once — on the shared modern registry that orphan lease\n // pinned a watcher until process shutdown.\n const inflight = new Map<string, Promise<boolean | undefined>>();\n\n return {\n name: 'filesystem-mcp-file',\n title: 'Workspace File',\n description: 'Read a file from the workspace. Subscribe to get updates when the file changes.',\n uriTemplate: FILESYSTEM_FILE_URI_TEMPLATE,\n annotations: { audience: ['assistant'], priority: 0.8 },\n // Without this the SDK falls back to its conservative `{ ttlMs: 0,\n // cacheScope: 'private' }`, making every file read uncacheable — and this\n // is the one resource with a live invalidation channel, so TTL and the\n // watcher compose exactly as the spec's caching section describes. The TTL\n // stays short because a non-subscriber gets no invalidation signal at all.\n cacheHint: { cacheScope: options.cacheScope ?? 'public', ttlMs: 5_000 },\n\n // No `list`: the template registers with `list: undefined` — readable but\n // not enumerable. Listing each allowed root as a concrete resource\n // duplicated the template and grew resources/list linearly with roots;\n // `list_roots` owns root discovery.\n\n async read(uri, _variables, _ctx: ServerContext) {\n // Decode via extractPath — the same decoder resources/subscribe uses — so\n // both consumers are symmetric with buildFileResourceUri's encoding. The\n // {+path} template variable arrives still percent-encoded, so validating\n // it directly would treat \"c%3A/proj/a.ts\" as a literal relative path;\n // no fallback to it here, or the two branches would validate different\n // strings. extractPath only fails past the template match on undecodable\n // percent-encoding, which is the caller's malformed URI.\n const rawPath = extractPath(uri.href);\n if (rawPath === undefined) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n 'Malformed file URI: path is not valid percent-encoding',\n );\n }\n await options.pathGuard.validateExistingPath(rawPath);\n const fs = new GuardedFileSystem(options.pathGuard);\n const readResult = await fs.readRaw(rawPath);\n\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: readResult.mimeType || 'application/octet-stream',\n ...(readResult.isBinary\n ? { blob: readResult.content.toString('base64') }\n : { text: readResult.content.toString('utf-8') }),\n },\n ],\n };\n },\n\n complete: {\n // Both ends speak the `{+path}` form (see encodeFileUriPath), not raw OS\n // paths: the partial arriving here is whatever this returned last, so the\n // decode mirrors the encode. An undecodable partial is matched as typed.\n path: async (value) => {\n const suggestions = await completer.suggest(decodeFileUriPath(value) ?? value);\n return suggestions.map(encodeFileUriPath);\n },\n },\n\n subscribe(uri, notify) {\n // Already subscribed on this connection: the watcher is live and the sink\n // is registered, so this is a no-op success rather than a second lease.\n if (leasedUris.has(uri)) return undefined;\n // A subscribe for this URI is mid-acquire: share its outcome instead of\n // taking a second lease the lease set cannot represent.\n const pending = inflight.get(uri);\n if (pending) return pending;\n\n const acquire = async (): Promise<boolean | undefined> => {\n const result = await registry.acquire(options.pathGuard, uri, notify, {\n markSubscribe: true,\n });\n if (result.ok) {\n leasedUris.add(uri);\n return undefined;\n }\n\n if (result.reason === 'bad-uri') {\n throw new ResourceNotFoundError(uri, `Cannot subscribe: not a filesystem URI`);\n }\n if (result.reason === 'invalid-path') {\n const err = result.error;\n if (isNotFoundish(err)) {\n throw new ResourceNotFoundError(uri, `Cannot subscribe to ${uri}: ${err.message}`);\n }\n Logger.warn(\n `Unexpected error validating path for watcher ${uri}: ${formatUnknownErrorMessage(err)}`,\n );\n throw err;\n }\n // Unsubscribed (or the registry destroyed) mid-await: the caller already\n // asked for this to stop, so there is nothing to reject.\n if (result.reason === 'stale') return undefined;\n // capped / attach-failed: `false` tells the handler to reject, since\n // undefined would report success with no watcher attached.\n return false;\n };\n\n const promise = acquire().finally(() => inflight.delete(uri));\n inflight.set(uri, promise);\n return promise;\n },\n\n unsubscribe(uri) {\n // Only release a lease this connection actually took.\n if (!leasedUris.delete(uri)) return;\n registry.release(uri);\n },\n\n destroy() {\n // Release what this connection still holds before the registry goes: on\n // the shared (modern) registry nothing else would ever end these leases.\n for (const uri of leasedUris) registry.release(uri);\n leasedUris.clear();\n if (ownsRegistry) registry.destroy();\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════\n// result\n// ═══════════════════════════════════════════════════════════════\n\nfunction createResultResource(options: ResourceRegistrationOptions): ResourceContract {\n return {\n name: 'filesystem-mcp-result',\n title: 'Cached Tool Result',\n description:\n 'Ephemeral cached tool output. Listed via resources/list; entries expire after the cache TTL.',\n mimeType: 'application/json',\n uriTemplate: 'filesystem-mcp://result/{id}',\n annotations: { audience: ['assistant'], priority: 0.3 },\n cacheHint: { cacheScope: 'private', ttlMs: 60_000 },\n list() {\n const store = options.resourceStore;\n const uris = store.keys(); // prunes expired first\n const resources: Resource[] = [];\n for (const uri of uris) {\n try {\n const entry = store.getEntry(uri);\n resources.push({\n uri: entry.uri,\n name: entry.name,\n mimeType: entry.mimeType,\n size: entry.size,\n });\n } catch (err) {\n // An entry may expire between keys() and getEntry; skip it.\n if (isFsError(err) && err.code === ErrorCode.NOT_FOUND) continue;\n throw err;\n }\n }\n // Recent-first: keys() returns insertion order, so the newest is last.\n resources.reverse();\n return { resources };\n },\n read(uri, variables) {\n const { id } = variables;\n if (typeof id !== 'string' || id.length === 0) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n 'Malformed result URI: missing {id}. Use the exact resourceUri returned by the tool.',\n );\n }\n\n let entry;\n try {\n entry = options.resourceStore.getEntry(uri.toString());\n } catch (err) {\n if (isFsError(err) && err.code === ErrorCode.NOT_FOUND) {\n throw new ResourceNotFoundError(\n uri.toString(),\n 'Cached result not found or expired. Re-run the tool to regenerate.',\n );\n }\n throw err;\n }\n return {\n contents: [{ uri: entry.uri, mimeType: entry.mimeType, text: entry.text }],\n };\n },\n };\n}\n\n// ═══════════════════════════════════════════════════════════════\n// export contracts\n// ═══════════════════════════════════════════════════════════════\n\nexport function getResourceContracts(options: ResourceRegistrationOptions): ResourceContract[] {\n return [\n createInstructionsResource(options),\n createResultResource(options),\n createFilesystemResource(options),\n ];\n}\n\n// ═══════════════════════════════════════════════════════════════\n// registrar\n// ═══════════════════════════════════════════════════════════════\n\nfunction wrapRead(contract: ResourceContract) {\n return async (uri: URL, variables: Record<string, string | string[]>, ctx: ServerContext) => {\n try {\n return await contract.read(uri, variables, ctx);\n } catch (error) {\n // The SDK brands ProtocolError with `static [Symbol.hasInstance]`, so this\n // holds across separately bundled SDK copies and realms.\n if (error instanceof ProtocolError) throw error;\n // A missing or out-of-root path is a not-found, not a malformed request.\n // The SDK puts ResourceNotFoundError on the wire as -32602 with\n // `data.uri`, which is what clients match on; -32002 is the older code\n // they also accept, and this SDK never emits it.\n if (isNotFoundish(error)) {\n throw new ResourceNotFoundError(uri.toString(), error.message);\n }\n // A remaining FsError (NOT_FILE, TOO_LARGE, ...) traces to the\n // caller-supplied URI; anything else is a server-side failure and must\n // not be blamed on the request.\n const msg = isFsError(error) ? error.message : formatUnknownErrorMessage(error);\n throw new ProtocolError(fsErrorCode(error), msg);\n }\n };\n}\n\nexport function registerResources(deps: ResourceRegistrarDeps): { dispose(): void } {\n const server = deps.server;\n const resourceContracts = getResourceContracts({ ...deps, readOnly: deps.readOnly ?? false });\n\n for (const contract of resourceContracts) {\n const config = {\n ...(contract.title !== undefined ? { title: contract.title } : {}),\n ...(contract.description !== undefined ? { description: contract.description } : {}),\n ...(contract.mimeType !== undefined ? { mimeType: contract.mimeType } : {}),\n ...(contract.annotations !== undefined ? { annotations: contract.annotations } : {}),\n ...(contract.cacheHint !== undefined ? { cacheHint: contract.cacheHint } : {}),\n };\n\n if (contract.uriTemplate) {\n const template = new ResourceTemplate(contract.uriTemplate, {\n list: contract.list,\n ...(contract.complete ? { complete: contract.complete } : {}),\n });\n\n server.registerResource(contract.name, template, config, wrapRead(contract));\n } else if (contract.uri) {\n server.registerResource(contract.name, contract.uri, config, (uri: URL, ctx: ServerContext) =>\n wrapRead(contract)(uri, {}, ctx),\n );\n }\n }\n\n // `resources/subscribe`/`unsubscribe` are 2025-era-only verbs; a modern\n // server answers `-32601 Method not found` for them, so registering these\n // handlers on a modern-era instance would dispatch to code no request can\n // reach. A legacy instance on the HTTP leg (the one built with a `notifier`)\n // lives for one request: a subscription accepted there would take a watcher\n // lease for an instance that is gone before the file changes. Leave the\n // handlers off so the SDK refuses the verb, and no lease is taken. The\n // predicate mirrors the capability gate in server.ts exactly, so the\n // handler is registered if and only if `resources.subscribe` is advertised.\n // sunset(SEP-2577): removal trigger in docs/adr/002-legacy-protocol-paths-sunset.md.\n const legacyHttp = deps.era === 'legacy' && deps.notifier !== undefined;\n if (deps.era !== 'modern' && !legacyHttp) {\n server.server.assertCanSetRequestHandler('resources/subscribe');\n server.server.assertCanSetRequestHandler('resources/unsubscribe');\n\n // One stable callback for the whole registrar, NOT one per subscribe. The\n // registry holds these in a Set keyed by identity, so a fresh closure per\n // request made a second `resources/subscribe` for the same URI register a\n // second sink: one file change then sent N notifications, and `unsubscribe`\n // (which only ends a lease) removed none of them. Subscribe is per-URI on\n // the wire, so the sink must be too — this makes it idempotent.\n const notifyUpdated = (updatedUri: string): void => {\n if (deps.notifier) {\n deps.notifier.resourceUpdated(updatedUri);\n return;\n }\n const updatePayload: ResourceUpdatedNotificationParams = { uri: updatedUri };\n // A failed notify means the connection went away; nothing to recover.\n void server.server.sendResourceUpdated(updatePayload).catch((err: unknown) => {\n Logger.debug('resource update not delivered', {\n uri: updatedUri,\n error: formatUnknownErrorMessage(err),\n });\n });\n };\n\n server.server.setRequestHandler(\n 'resources/subscribe',\n async (req: { params: SubscribeRequestParams }) => {\n const requestedResource = resourceUrlFromServerUrl(req.params.uri);\n let foundMatch = false;\n // A resource that exists but has no watcher (the instructions text, a\n // cached result) is NOT a not-found: reporting it as one told clients a\n // URI they can list and read does not exist. Track the two cases apart.\n let knownButNotSubscribable = false;\n for (const contract of resourceContracts) {\n const configured = contract.uri ?? contract.uriTemplate.split('{')[0];\n if (!contract.subscribe) {\n if (\n configured &&\n checkResourceAllowed({ requestedResource, configuredResource: configured })\n ) {\n knownButNotSubscribable = true;\n }\n continue;\n }\n if (!configured) continue;\n if (\n checkResourceAllowed({\n requestedResource,\n configuredResource: configured,\n })\n ) {\n foundMatch = true;\n const subscribeResult = await contract.subscribe(\n requestedResource.toString(),\n notifyUpdated,\n );\n if (subscribeResult === false) {\n // InternalError for want of anything better: ProtocolErrorCode\n // has no resource-limit member, and the message already names\n // the actionable cause.\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `Subscription rejected: no watcher attached (watcher limit ${MAX_WATCHERS} reached, or fs.watch failed to start).`,\n );\n }\n break;\n }\n }\n if (!foundMatch) {\n if (knownButNotSubscribable) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Resource ${requestedResource.toString()} does not support subscriptions; only ${FILESYSTEM_FILE_URI_TEMPLATE} does. Read it again for the current contents.`,\n );\n }\n throw new ResourceNotFoundError(\n requestedResource.toString(),\n `Resource not found: ${requestedResource.toString()}`,\n );\n }\n return {};\n },\n );\n\n server.server.setRequestHandler(\n 'resources/unsubscribe',\n (req: { params: UnsubscribeRequestParams }) => {\n // Route by URI prefix, mirroring the subscribe handler: a broadcast\n // to every contract works while only one is subscribable, but hands a\n // second subscribable contract someone else's URI the day it appears.\n const requestedResource = resourceUrlFromServerUrl(req.params.uri);\n for (const contract of resourceContracts) {\n if (!contract.unsubscribe) continue;\n const configured = contract.uri ?? contract.uriTemplate.split('{')[0];\n if (!configured) continue;\n if (checkResourceAllowed({ requestedResource, configuredResource: configured })) {\n contract.unsubscribe(requestedResource.toString());\n }\n }\n return {};\n },\n );\n }\n\n return {\n dispose(): void {\n for (const contract of resourceContracts) {\n if (contract.destroy) {\n contract.destroy();\n }\n }\n },\n };\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":"AAAA,OAAO,KAAK,EAGV,cAAc,EACf,MAAM,8BAA8B,CAAC;AACtC,OAAO,E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gB,CAAC;AACpD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAgBlE,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,GAAG,EAAE,SAAS,CAAC;IACxB,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,mBAAmB,IAAI,IAAI,CAAC;CAC7B;AAED,wBAAsB,YAAY,CAChC,OAAO,GAAE,aAAkB,EAC3B,SAAS,CAAC,EAAE;IACV,0EAA0E;IAC1E,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,+CAA+C;IAC/C,QAAQ,CAAC,EAAE,cAAc,CAAC;IAC1B;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB;;;;;OAKG;IACH,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,iBAAiB,CAAC;IAC9B,qFAAqF;IACrF,GAAG,CAAC,EAAE,QAAQ,GAAG,QAAQ,CAAC;IAC1B;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GACA,OAAO,CAAC,uBAAuB,CAAC,CAkHlC"}
|
package/dist/server.js
CHANGED
|
@@ -17,9 +17,14 @@ export async function createServer(options = {}, extraDeps) {
|
|
|
17
17
|
// `resources.subscribe` stays advertised on both eras: the verb itself is
|
|
18
18
|
// 2025-only, but with enforceStrictCapabilities the SDK also gates outbound
|
|
19
19
|
// `notifications/resources/updated` — which the modern `subscriptions/listen`
|
|
20
|
-
// stream delivers — on this same capability bit.
|
|
20
|
+
// stream delivers — on this same capability bit. The one exception is a
|
|
21
|
+
// legacy instance on the HTTP leg (era 'legacy' with a notifier): it serves
|
|
22
|
+
// one request, registers no subscribe handler (resources.ts, same
|
|
23
|
+
// predicate) and sends no notification of any kind — there is no stream to
|
|
24
|
+
// send it on — so neither `subscribe` nor `listChanged` is advertised.
|
|
25
|
+
const legacyHttp = extraDeps?.era === 'legacy' && extraDeps.notifier !== undefined;
|
|
21
26
|
const capabilities = {
|
|
22
|
-
resources: { subscribe:
|
|
27
|
+
resources: { subscribe: !legacyHttp, listChanged: !legacyHttp },
|
|
23
28
|
tools: {},
|
|
24
29
|
prompts: {},
|
|
25
30
|
completions: {},
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAEzD,OAAO,WAAW,MAAM,iBAAiB,CAAC,OAAO,IAAI,EAAE,MAAM,EAAE,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC3E,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,kEAAkE;AAClE,YAAY;AACZ,kEAAkE;AAElE,MAAM,EACJ,OAAO,EAAE,cAAc,EACvB,WAAW,EAAE,kBAAkB,EAC/B,QAAQ,EAAE,eAAe,GAC1B,GAAG,WAAW,CAAC;AAQhB,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,UAAyB,EAAE,EAC3B,SAkCC;IAED,0EAA0E;IAC1E,4EAA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AAa,EAAE;QAAE,MAAM,SAAS,CAAC,2BAA2B,EAAE,CAAC;IAE9E,MAAM,IAAI,GAAG;QACX,MAAM;QACN,SAAS;QACT,SAAS;QACT,aAAa;QACb,UAAU;QACV,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC/C,GAAG,CAAC,SAAS,EAAE,eAAe,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,SAAS,CAAC,eAAe,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACrF,GAAG,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,SAAS,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAChE,GAAG,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,SAAS,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAClD,CAAC;IAEF,MAAM,kBAAkB,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACnD,eAAe,CAAC,IAAI,CAAC,CAAC;IACtB,aAAa,CAAC,IAAI,CAAC,CAAC;IAEpB,yEAAyE;IACzE,MAAM,SAAS,GAAG,SAAS,EAAE,SAAS,KAAK,SAAS,CAAC;IACrD,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,OAAO;QACL,GAAG,EAAE,MAAM;QACX,SAAS;QACT,mBAAmB;YACjB,IAAI,SAAS;gBAAE,OAAO;YACtB,SAAS,GAAG,IAAI,CAAC;YACjB,IAAI,SAAS;gBAAE,SAAS,CAAC,KAAK,EAAE,CAAC;YACjC,kBAAkB,CAAC,OAAO,EAAE,CAAC;QAC/B,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n Implementation,\n ServerCapabilities,\n ServerNotifier,\n} from '@modelcontextprotocol/server';\nimport { McpServer } from '@modelcontextprotocol/server';\n\nimport packageJson from '../package.json' with { type: 'json' };\nimport { requestStateCodec } from './core/input-required.js';\nimport { Logger } from './core/observability.js';\nimport { PageSnapshotStore } from './core/page-store.js';\nimport type { ServerOptions } from './core/path.js';\nimport { PathGuard } from './core/path.js';\nimport { ResourceStore } from './core/store.js';\nimport type { WatcherRegistry } from './core/watcher-registry.js';\nimport { INSTRUCTIONS_SUMMARY, INSTRUCTIONS_URI } from './instructions.js';\nimport { registerPrompts } from './prompts.js';\nimport { registerResources } from './resources.js';\nimport { registerTools } from './tools/index.js';\n\n// ═══════════════════════════════════════════════════════════════\n// bootstrap\n// ═══════════════════════════════════════════════════════════════\n\nconst {\n version: SERVER_VERSION,\n description: SERVER_DESCRIPTION,\n homepage: SERVER_HOMEPAGE,\n} = packageJson;\n\nexport interface FilesystemServerContext {\n readonly mcp: McpServer;\n readonly pathGuard: PathGuard;\n disposeRuntimeState(): void;\n}\n\nexport async function createServer(\n options: ServerOptions = {},\n extraDeps?: {\n /** Shared file-watcher registry for the modern (per-request) HTTP leg. */\n watcherRegistry?: WatcherRegistry;\n /** Modern-leg typed notification publisher. */\n notifier?: ServerNotifier;\n /**\n * Guard to use instead of constructing one. The HTTP leg builds a single\n * guard for the whole endpoint and passes it to every per-request instance,\n * so an accepted access grant survives the request that accepted it (R8) and\n * the listen-watcher path validates against the same allowed set. Omitted on\n * stdio, where the instance is pinned for the connection and owns its guard.\n */\n pathGuard?: PathGuard;\n /**\n * Store to use instead of constructing one. The HTTP modern leg shares one\n * store across every per-request instance, so a result a tool externalized\n * in one POST survives to the follow-up resources/read. Omitted on stdio,\n * where the pinned instance owns its store for the connection.\n */\n resourceStore?: ResourceStore;\n /**\n * Pagination snapshots shared by every modern HTTP request. Omitted on\n * stdio, where the connection-owned context clears its store on close.\n */\n pageStore?: PageSnapshotStore;\n /** The protocol era this instance serves; omitted where the caller does not know. */\n era?: 'legacy' | 'modern';\n /**\n * The resolved HTTP credential, from `--api-key` or `API_KEY`. Lives here\n * rather than on `ServerOptions` because that object is `PathGuard`'s\n * constructor argument and is exposed on its public `options` field — a\n * bearer secret has no business being reachable from a tool handler.\n */\n apiKey?: string;\n },\n): Promise<FilesystemServerContext> {\n // `resources.subscribe` stays advertised on both eras: the verb itself is\n // 2025-only, but with enforceStrictCapabilities the SDK also gates outbound\n // `notifications/resources/updated` — which the modern `subscriptions/listen`\n // stream delivers — on this same capability bit.\n const capabilities = {\n resources: { subscribe: true, listChanged: true },\n tools: {},\n prompts: {},\n completions: {},\n } satisfies ServerCapabilities;\n\n const cacheScope: 'private' | 'public' = extraDeps?.apiKey ? 'private' : 'public';\n const serverConfig: NonNullable<ConstructorParameters<typeof McpServer>[1]> = {\n capabilities,\n enforceStrictCapabilities: true,\n cacheHints: {\n 'tools/list': { ttlMs: 3_600_000, cacheScope },\n 'prompts/list': { ttlMs: 3_600_000, cacheScope },\n // Always private, never `cacheScope`: this list enumerates the\n // ResourceStore, so its entries are one caller's externalized tool output\n // — the same entries whose own read hint is `private` (resources.ts). The\n // other four lists are the same for every caller and follow the key, and\n // they are built from frozen module-level arrays that cannot change at\n // runtime, so an hour is honest: a shorter hint only buys the client a\n // re-fetch of bytes that cannot have differed, at the cost of the prompt\n // cache stability the spec asks deterministic ordering to preserve.\n 'resources/list': { ttlMs: 30_000, cacheScope: 'private' },\n 'resources/templates/list': { ttlMs: 3_600_000, cacheScope },\n 'server/discover': { ttlMs: 3_600_000, cacheScope },\n },\n // Multi-round-trip `requestState` integrity (protocol revision 2026-07-28):\n // the codec verifies the HMAC on every retried round before the handler\n // runs, so a tampered or expired state is rejected as `-32602` rather than\n // trusted. The decoded `PendingState` reaches handlers via\n // `ctx.mcpReq.requestState<T>()`.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n requestState: { verify: requestStateCodec.verify },\n };\n\n serverConfig.instructions =\n `${INSTRUCTIONS_SUMMARY} ` +\n `For full guidance, read ${INSTRUCTIONS_URI} or run the get-help prompt.`;\n\n const implementation: Implementation = {\n name: 'filesystem-mcp',\n title: 'Filesystem MCP',\n version: SERVER_VERSION,\n ...(SERVER_DESCRIPTION ? { description: SERVER_DESCRIPTION } : {}),\n ...(SERVER_HOMEPAGE ? { websiteUrl: SERVER_HOMEPAGE } : {}),\n };\n const server = new McpServer(implementation, serverConfig);\n server.server.fallbackNotificationHandler = (notification) => {\n Logger.debug('Unhandled client notification', { method: notification.method });\n return Promise.resolve();\n };\n\n // A failed send means the connection went away; nothing to recover.\n const resourceStore =\n extraDeps?.resourceStore ??\n new ResourceStore(() => {\n if (extraDeps?.notifier) {\n extraDeps.notifier.resourcesChanged();\n return;\n }\n void server.server.sendResourceListChanged().catch((error: unknown) => {\n Logger.debug('resource list_changed not delivered', { error: String(error) });\n });\n });\n const pageStore = extraDeps?.pageStore ?? new PageSnapshotStore();\n\n const pathGuard = extraDeps?.pathGuard ?? new PathGuard(options);\n // Recompute once per guard, keyed on the guard's own state rather than on\n // whether it was injected — an injected-but-uninitialized guard would\n // otherwise deny every path. Not unconditional: the HTTP leg shares one guard\n // across a fresh instance per request, and a repeat recompute would both redo\n // the root resolution per request and race a concurrent `applyGrant`, which\n // commits under a mutation lock this call does not take.\n if (!pathGuard.isInitialized()) await pathGuard.recomputeAllowedDirectories();\n\n const deps = {\n server,\n pathGuard,\n pageStore,\n resourceStore,\n cacheScope,\n ...(options.readOnly ? { readOnly: true } : {}),\n ...(extraDeps?.watcherRegistry ? { watcherRegistry: extraDeps.watcherRegistry } : {}),\n ...(extraDeps?.notifier ? { notifier: extraDeps.notifier } : {}),\n ...(extraDeps?.era ? { era: extraDeps.era } : {}),\n };\n\n const resourceDisposable = registerResources(deps);\n registerPrompts(deps);\n registerTools(deps);\n\n // False when the store is shared across instances and outlives this one.\n const ownsPages = extraDeps?.pageStore === undefined;\n let cleanedUp = false;\n return {\n mcp: server,\n pathGuard,\n disposeRuntimeState() {\n if (cleanedUp) return;\n cleanedUp = true;\n if (ownsPages) pageStore.clear();\n resourceDisposable.dispose();\n },\n };\n}\n"]}
|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AAU;QACV,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC/C,GAAG,CAAC,SAAS,EAAE,eAAe,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,SAAS,CAAC,eAAe,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACrF,GAAG,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,SAAS,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAChE,GAAG,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,SAAS,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAClD,CAAC;IAEF,MAAM,kBAAkB,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACnD,eAAe,CAAC,IAAI,CAAC,CAAC;IACtB,aAAa,CAAC,IAAI,CAAC,CAAC;IAEpB,yEAAyE;IACzE,MAAM,SAAS,GAAG,SAAS,EAAE,SAAS,KAAK,SAAS,CAAC;IACrD,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,OAAO;QACL,GAAG,EAAE,MAAM;QACX,SAAS;QACT,mBAAmB;YACjB,IAAI,SAAS;gBAAE,OAAO;YACtB,SAAS,GAAG,IAAI,CAAC;YACjB,IAAI,SAAS;gBAAE,SAAS,CAAC,KAAK,EAAE,CAAC;YACjC,kBAAkB,CAAC,OAAO,EAAE,CAAC;QAC/B,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n Implementation,\n ServerCapabilities,\n ServerNotifier,\n} from '@modelcontextprotocol/server';\nimport { McpServer } from '@modelcontextprotocol/server';\n\nimport packageJson from '../package.json' with { type: 'json' };\nimport { requestStateCodec } from './core/input-required.js';\nimport { Logger } from './core/observability.js';\nimport { PageSnapshotStore } from './core/page-store.js';\nimport type { ServerOptions } from './core/path.js';\nimport { PathGuard } from './core/path.js';\nimport { ResourceStore } from './core/store.js';\nimport type { WatcherRegistry } from './core/watcher-registry.js';\nimport { INSTRUCTIONS_SUMMARY, INSTRUCTIONS_URI } from './instructions.js';\nimport { registerPrompts } from './prompts.js';\nimport { registerResources } from './resources.js';\nimport { registerTools } from './tools/index.js';\n\n// ═══════════════════════════════════════════════════════════════\n// bootstrap\n// ═══════════════════════════════════════════════════════════════\n\nconst {\n version: SERVER_VERSION,\n description: SERVER_DESCRIPTION,\n homepage: SERVER_HOMEPAGE,\n} = packageJson;\n\nexport interface FilesystemServerContext {\n readonly mcp: McpServer;\n readonly pathGuard: PathGuard;\n disposeRuntimeState(): void;\n}\n\nexport async function createServer(\n options: ServerOptions = {},\n extraDeps?: {\n /** Shared file-watcher registry for the modern (per-request) HTTP leg. */\n watcherRegistry?: WatcherRegistry;\n /** Modern-leg typed notification publisher. */\n notifier?: ServerNotifier;\n /**\n * Guard to use instead of constructing one. The HTTP leg builds a single\n * guard for the whole endpoint and passes it to every per-request instance,\n * so an accepted access grant survives the request that accepted it (R8) and\n * the listen-watcher path validates against the same allowed set. Omitted on\n * stdio, where the instance is pinned for the connection and owns its guard.\n */\n pathGuard?: PathGuard;\n /**\n * Store to use instead of constructing one. The HTTP modern leg shares one\n * store across every per-request instance, so a result a tool externalized\n * in one POST survives to the follow-up resources/read. Omitted on stdio,\n * where the pinned instance owns its store for the connection.\n */\n resourceStore?: ResourceStore;\n /**\n * Pagination snapshots shared by every modern HTTP request. Omitted on\n * stdio, where the connection-owned context clears its store on close.\n */\n pageStore?: PageSnapshotStore;\n /** The protocol era this instance serves; omitted where the caller does not know. */\n era?: 'legacy' | 'modern';\n /**\n * The resolved HTTP credential, from `--api-key` or `API_KEY`. Lives here\n * rather than on `ServerOptions` because that object is `PathGuard`'s\n * constructor argument and is exposed on its public `options` field — a\n * bearer secret has no business being reachable from a tool handler.\n */\n apiKey?: string;\n },\n): Promise<FilesystemServerContext> {\n // `resources.subscribe` stays advertised on both eras: the verb itself is\n // 2025-only, but with enforceStrictCapabilities the SDK also gates outbound\n // `notifications/resources/updated` — which the modern `subscriptions/listen`\n // stream delivers — on this same capability bit. The one exception is a\n // legacy instance on the HTTP leg (era 'legacy' with a notifier): it serves\n // one request, registers no subscribe handler (resources.ts, same\n // predicate) and sends no notification of any kind — there is no stream to\n // send it on — so neither `subscribe` nor `listChanged` is advertised.\n const legacyHttp = extraDeps?.era === 'legacy' && extraDeps.notifier !== undefined;\n const capabilities = {\n resources: { subscribe: !legacyHttp, listChanged: !legacyHttp },\n tools: {},\n prompts: {},\n completions: {},\n } satisfies ServerCapabilities;\n\n const cacheScope: 'private' | 'public' = extraDeps?.apiKey ? 'private' : 'public';\n const serverConfig: NonNullable<ConstructorParameters<typeof McpServer>[1]> = {\n capabilities,\n enforceStrictCapabilities: true,\n cacheHints: {\n 'tools/list': { ttlMs: 3_600_000, cacheScope },\n 'prompts/list': { ttlMs: 3_600_000, cacheScope },\n // Always private, never `cacheScope`: this list enumerates the\n // ResourceStore, so its entries are one caller's externalized tool output\n // — the same entries whose own read hint is `private` (resources.ts). The\n // other four lists are the same for every caller and follow the key, and\n // they are built from frozen module-level arrays that cannot change at\n // runtime, so an hour is honest: a shorter hint only buys the client a\n // re-fetch of bytes that cannot have differed, at the cost of the prompt\n // cache stability the spec asks deterministic ordering to preserve.\n 'resources/list': { ttlMs: 30_000, cacheScope: 'private' },\n 'resources/templates/list': { ttlMs: 3_600_000, cacheScope },\n 'server/discover': { ttlMs: 3_600_000, cacheScope },\n },\n // Multi-round-trip `requestState` integrity (protocol revision 2026-07-28):\n // the codec verifies the HMAC on every retried round before the handler\n // runs, so a tampered or expired state is rejected as `-32602` rather than\n // trusted. The decoded `PendingState` reaches handlers via\n // `ctx.mcpReq.requestState<T>()`.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n requestState: { verify: requestStateCodec.verify },\n };\n\n serverConfig.instructions =\n `${INSTRUCTIONS_SUMMARY} ` +\n `For full guidance, read ${INSTRUCTIONS_URI} or run the get-help prompt.`;\n\n const implementation: Implementation = {\n name: 'filesystem-mcp',\n title: 'Filesystem MCP',\n version: SERVER_VERSION,\n ...(SERVER_DESCRIPTION ? { description: SERVER_DESCRIPTION } : {}),\n ...(SERVER_HOMEPAGE ? { websiteUrl: SERVER_HOMEPAGE } : {}),\n };\n const server = new McpServer(implementation, serverConfig);\n server.server.fallbackNotificationHandler = (notification) => {\n Logger.debug('Unhandled client notification', { method: notification.method });\n return Promise.resolve();\n };\n\n // A failed send means the connection went away; nothing to recover.\n const resourceStore =\n extraDeps?.resourceStore ??\n new ResourceStore(() => {\n if (extraDeps?.notifier) {\n extraDeps.notifier.resourcesChanged();\n return;\n }\n void server.server.sendResourceListChanged().catch((error: unknown) => {\n Logger.debug('resource list_changed not delivered', { error: String(error) });\n });\n });\n const pageStore = extraDeps?.pageStore ?? new PageSnapshotStore();\n\n const pathGuard = extraDeps?.pathGuard ?? new PathGuard(options);\n // Recompute once per guard, keyed on the guard's own state rather than on\n // whether it was injected — an injected-but-uninitialized guard would\n // otherwise deny every path. Not unconditional: the HTTP leg shares one guard\n // across a fresh instance per request, and a repeat recompute would both redo\n // the root resolution per request and race a concurrent `applyGrant`, which\n // commits under a mutation lock this call does not take.\n if (!pathGuard.isInitialized()) await pathGuard.recomputeAllowedDirectories();\n\n const deps = {\n server,\n pathGuard,\n pageStore,\n resourceStore,\n cacheScope,\n ...(options.readOnly ? { readOnly: true } : {}),\n ...(extraDeps?.watcherRegistry ? { watcherRegistry: extraDeps.watcherRegistry } : {}),\n ...(extraDeps?.notifier ? { notifier: extraDeps.notifier } : {}),\n ...(extraDeps?.era ? { era: extraDeps.era } : {}),\n };\n\n const resourceDisposable = registerResources(deps);\n registerPrompts(deps);\n registerTools(deps);\n\n // False when the store is shared across instances and outlives this one.\n const ownsPages = extraDeps?.pageStore === undefined;\n let cleanedUp = false;\n return {\n mcp: server,\n pathGuard,\n disposeRuntimeState() {\n if (cleanedUp) return;\n cleanedUp = true;\n if (ownsPages) pageStore.clear();\n resourceDisposable.dispose();\n },\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../../src/tools/create.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../../src/tools/create.ts"],"names":[],"mappings":"AAiGA,eAAO,MAAM,MAAM,mCAoOjB,CAAC"}
|
package/dist/tools/create.js
CHANGED
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
import { basename, dirname } from 'node:path';
|
|
2
2
|
import * as z from 'zod/v4';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { processInParallel } from '../core/concurrency.js';
|
|
4
|
+
import { ErrorCode, formatUnknownErrorMessage, FsError, rethrowIfAborted } from '../core/errors.js';
|
|
5
|
+
import { buildFileResourceLink, buildFileResourceUri, buildWrittenFileMeta, } from '../core/file-uri.js';
|
|
6
|
+
import { countFileLines, destExists } from '../core/fs.js';
|
|
7
|
+
import { choiceInput, confirmKey, pendingRoundTrip, readAcceptedChoice, } from '../core/input-required.js';
|
|
8
|
+
import { detectMimeFromContent, MIME_SAMPLE_SIZE } from '../core/mime.js';
|
|
5
9
|
import { FileKind, IsoDateTime, NonNegInt, PathFailureSchema, RequiredPath, } from '../core/schema.js';
|
|
6
|
-
import { getMaxTextFileSize } from '../core/util.js';
|
|
10
|
+
import { getMaxTextFileSize, PARALLEL_CONCURRENCY } from '../core/util.js';
|
|
7
11
|
import { isTotalFailure, runOverPaths } from './batch.js';
|
|
8
12
|
import { defineTool } from './define.js';
|
|
13
|
+
const EPOCH = new Date(0);
|
|
9
14
|
const CreateFileItemSchema = z.strictObject({
|
|
10
15
|
path: RequiredPath.describe('Absolute path where the file will be created'),
|
|
11
16
|
content: z
|
|
@@ -14,6 +19,14 @@ const CreateFileItemSchema = z.strictObject({
|
|
|
14
19
|
message: 'Content exceeds maximum allowed text file size',
|
|
15
20
|
})
|
|
16
21
|
.describe('Text content to write, verbatim.'),
|
|
22
|
+
append: z
|
|
23
|
+
.boolean()
|
|
24
|
+
.optional()
|
|
25
|
+
.describe('Append the content to the end of the file instead of overwriting; creates the file if it does not exist'),
|
|
26
|
+
overwrite: z
|
|
27
|
+
.boolean()
|
|
28
|
+
.optional()
|
|
29
|
+
.describe('Replace an existing file without asking the user; without it an existing file prompts for confirmation'),
|
|
17
30
|
});
|
|
18
31
|
const CreateFileResultSchema = z.strictObject({
|
|
19
32
|
path: z.string().describe('Resolved absolute path of the created file'),
|
|
@@ -23,7 +36,8 @@ const CreateFileResultSchema = z.strictObject({
|
|
|
23
36
|
kind: FileKind.describe('Broad file kind: text, binary, image, audio, or pdf'),
|
|
24
37
|
resourceUri: z
|
|
25
38
|
.string()
|
|
26
|
-
.
|
|
39
|
+
.optional()
|
|
40
|
+
.describe('Resource URI pointing to the created file content in the resource store; omitted when the resulting file exceeds the text-size cap, which the store would reject'),
|
|
27
41
|
created: IsoDateTime.describe('File creation timestamp (ISO 8601 UTC)'),
|
|
28
42
|
modified: IsoDateTime.describe('File last-modification timestamp (ISO 8601 UTC)'),
|
|
29
43
|
});
|
|
@@ -40,13 +54,19 @@ const CreateOutputSchema = z.strictObject({
|
|
|
40
54
|
.array(PathFailureSchema)
|
|
41
55
|
.optional()
|
|
42
56
|
.describe('Files that failed to create with per-file error details'),
|
|
57
|
+
skipped: z
|
|
58
|
+
.array(z.string())
|
|
59
|
+
.optional()
|
|
60
|
+
.describe('Paths left untouched because the user chose Skip'),
|
|
43
61
|
});
|
|
44
62
|
export const CREATE = defineTool({
|
|
45
63
|
name: 'create',
|
|
46
64
|
title: 'Create Files',
|
|
47
|
-
description: 'Create one or more files (max 100),
|
|
65
|
+
description: 'Create one or more files (max 100), creating parent directories as needed. ' +
|
|
48
66
|
'Pass files: [{ path, content }] — there is no single-path form. ' +
|
|
49
|
-
'
|
|
67
|
+
'An existing file prompts the user to confirm the overwrite, so the call returns without writing ' +
|
|
68
|
+
'anything until that confirmation comes back; set overwrite: true on an entry to replace it without the prompt. ' +
|
|
69
|
+
'Set append: true on an entry to add to the end of an existing file (created if missing) instead of overwriting.',
|
|
50
70
|
input: CreateInputSchema,
|
|
51
71
|
output: CreateOutputSchema,
|
|
52
72
|
annotations: {
|
|
@@ -57,15 +77,138 @@ export const CREATE = defineTool({
|
|
|
57
77
|
},
|
|
58
78
|
accessPaths: (args) => args.files.map((f) => f.path),
|
|
59
79
|
run: async (args, ctx) => {
|
|
80
|
+
// Phase 1 (no mutation): which entries would replace a file that exists
|
|
81
|
+
// right now? Those need the user's word before anything is written (R14).
|
|
82
|
+
// append never destroys, and overwrite: true is that word given up front.
|
|
83
|
+
// A path that fails validation here is left for runOverPaths to report.
|
|
84
|
+
// A file that appears between rounds needs no re-stat before the write:
|
|
85
|
+
// the retry re-plans, and the grown pending set fails the R9 check.
|
|
86
|
+
const { results: planned } = await processInParallel(args.files, async (entry) => {
|
|
87
|
+
if (entry.append || entry.overwrite)
|
|
88
|
+
return undefined;
|
|
89
|
+
try {
|
|
90
|
+
const validPath = await ctx.fs.pathGuard.validatePathForWrite(entry.path);
|
|
91
|
+
return (await destExists(ctx.fs, validPath, 'create')) ? validPath : undefined;
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
rethrowIfAborted(error);
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
}, PARALLEL_CONCURRENCY, ctx.signal);
|
|
98
|
+
const pendingByPath = new Map();
|
|
99
|
+
for (const { index, value } of planned) {
|
|
100
|
+
const requested = args.files[index]?.path;
|
|
101
|
+
if (value && requested)
|
|
102
|
+
pendingByPath.set(requested, value);
|
|
103
|
+
}
|
|
104
|
+
const pendingSorted = [...new Set(pendingByPath.values())].sort();
|
|
105
|
+
if (pendingSorted.length > 0) {
|
|
106
|
+
// Round 1 returns input_required; a retry whose verified state does not
|
|
107
|
+
// bind this overwrite set throws (R9) via `pendingRoundTrip`.
|
|
108
|
+
const round = await pendingRoundTrip({
|
|
109
|
+
op: 'create',
|
|
110
|
+
pending: pendingSorted,
|
|
111
|
+
requestState: ctx.requestState,
|
|
112
|
+
clientCapabilities: ctx.clientCapabilities,
|
|
113
|
+
buildInputs: (paths) => paths.map((target, i) => choiceInput(confirmKey(i), `"${target}" already exists. Overwrite it?`, [
|
|
114
|
+
'overwrite',
|
|
115
|
+
'skip',
|
|
116
|
+
])),
|
|
117
|
+
});
|
|
118
|
+
if (round !== undefined)
|
|
119
|
+
return round;
|
|
120
|
+
}
|
|
60
121
|
const batch = await runOverPaths({ files: args.files }, ctx, async ({ path, override }) => {
|
|
61
122
|
const content = override?.content ?? '';
|
|
123
|
+
const pendingPath = pendingByPath.get(path);
|
|
124
|
+
if (pendingPath !== undefined) {
|
|
125
|
+
const key = confirmKey(pendingSorted.indexOf(pendingPath));
|
|
126
|
+
const choice = readAcceptedChoice(ctx.inputResponses, key);
|
|
127
|
+
if (choice === 'skip')
|
|
128
|
+
return { skipped: path };
|
|
129
|
+
if (choice !== 'overwrite') {
|
|
130
|
+
throw new FsError(ErrorCode.CANCELLED, `create cancelled: overwrite of "${path}" was declined or missing`, path);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
62
133
|
await ctx.fs.mkdir(dirname(path), { recursive: true });
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
134
|
+
// Overwrite: file content == `content`, so content-derived meta is
|
|
135
|
+
// exact and the atomic temp+rename write protects the existing mode.
|
|
136
|
+
// Append: the resulting file is everything that was there plus
|
|
137
|
+
// `content`, so size/created/modified come from a real post-append
|
|
138
|
+
// stat, MIME from the resulting file's leading bytes, and the line
|
|
139
|
+
// count streams the file — reading a multi-GB log back whole is the
|
|
140
|
+
// round-trip append exists to avoid.
|
|
141
|
+
let validPath;
|
|
142
|
+
let meta;
|
|
143
|
+
let created;
|
|
144
|
+
let modified;
|
|
145
|
+
if (override?.append) {
|
|
146
|
+
const appended = await ctx.fs.appendFile(path, content, {
|
|
147
|
+
encoding: 'utf-8',
|
|
148
|
+
signal: ctx.signal,
|
|
149
|
+
});
|
|
150
|
+
validPath = appended.validPath;
|
|
151
|
+
// The append is the commit point: the bytes are on disk, so
|
|
152
|
+
// everything below is best-effort RESULT METADATA, not part of the
|
|
153
|
+
// write. It runs unwired to ctx.signal, and a metadata failure
|
|
154
|
+
// degrades the result instead of failing it — either would report
|
|
155
|
+
// the append as failed and a client retry would append twice. The
|
|
156
|
+
// stat covers the committed validPath, never the input path: a
|
|
157
|
+
// symlink there could have been swapped between write and stat,
|
|
158
|
+
// and the result must describe the file the bytes landed in.
|
|
159
|
+
let stats;
|
|
160
|
+
let mimeType;
|
|
161
|
+
let kind;
|
|
162
|
+
let lineCount = 0;
|
|
163
|
+
try {
|
|
164
|
+
stats = (await ctx.fs.stat(appended.validPath)).stats;
|
|
165
|
+
// Sniff the resulting file's leading bytes, not the appended
|
|
166
|
+
// chunk: text appended to a binary file is still a binary file.
|
|
167
|
+
const sample = await ctx.fs.readLeadingSample(appended.validPath, MIME_SAMPLE_SIZE);
|
|
168
|
+
const mimeInfo = detectMimeFromContent(appended.validPath, sample);
|
|
169
|
+
mimeType = mimeInfo.mimeType;
|
|
170
|
+
kind = mimeInfo.kind;
|
|
171
|
+
lineCount = await countFileLines(appended.validPath);
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
ctx.log?.('warning', `create append: result metadata degraded for ${appended.validPath}: ${formatUnknownErrorMessage(error)}`, 'create');
|
|
175
|
+
// A POSIX mode-0222 file appends fine but cannot be opened 'r';
|
|
176
|
+
// fall back to the chunk for MIME (an approximation) and report
|
|
177
|
+
// the line count as unknown-as-zero rather than fail the append.
|
|
178
|
+
const mimeInfo = detectMimeFromContent(appended.validPath, content);
|
|
179
|
+
mimeType = mimeInfo.mimeType;
|
|
180
|
+
kind = mimeInfo.kind;
|
|
181
|
+
}
|
|
182
|
+
// The resource store serves this URI via readRaw, which rejects
|
|
183
|
+
// files over the text-size cap with TOO_LARGE — never advertise a
|
|
184
|
+
// link the store deterministically cannot serve. A failed stat
|
|
185
|
+
// leaves the size unknown, so nothing is advertised either.
|
|
186
|
+
const servable = stats !== undefined && stats.size <= getMaxTextFileSize();
|
|
187
|
+
const size = stats?.size ?? 0;
|
|
188
|
+
meta = {
|
|
189
|
+
size,
|
|
190
|
+
lineCount,
|
|
191
|
+
mimeType,
|
|
192
|
+
kind,
|
|
193
|
+
resourceUri: servable ? buildFileResourceUri(appended.validPath) : undefined,
|
|
194
|
+
resourceLink: servable && ctx.resourceStore
|
|
195
|
+
? buildFileResourceLink(appended.validPath, mimeType, size)
|
|
196
|
+
: undefined,
|
|
197
|
+
};
|
|
198
|
+
created = (stats?.birthtime ?? EPOCH).toISOString();
|
|
199
|
+
modified = (stats?.mtime ?? EPOCH).toISOString();
|
|
200
|
+
}
|
|
201
|
+
else {
|
|
202
|
+
const written = await ctx.fs.writeFile(path, content, {
|
|
203
|
+
encoding: 'utf-8',
|
|
204
|
+
signal: ctx.signal,
|
|
205
|
+
});
|
|
206
|
+
validPath = written.validPath;
|
|
207
|
+
const fileStats = (await ctx.fs.stat(path, { signal: ctx.signal })).stats;
|
|
208
|
+
created = fileStats.birthtime.toISOString();
|
|
209
|
+
modified = fileStats.mtime.toISOString();
|
|
210
|
+
meta = buildWrittenFileMeta(written.validPath, content, ctx.resourceStore);
|
|
211
|
+
}
|
|
69
212
|
const file = {
|
|
70
213
|
path: validPath,
|
|
71
214
|
size: meta.size,
|
|
@@ -73,19 +216,24 @@ export const CREATE = defineTool({
|
|
|
73
216
|
mimeType: meta.mimeType,
|
|
74
217
|
kind: meta.kind,
|
|
75
218
|
resourceUri: meta.resourceUri,
|
|
76
|
-
created
|
|
77
|
-
modified
|
|
219
|
+
created,
|
|
220
|
+
modified,
|
|
78
221
|
};
|
|
79
222
|
return meta.resourceLink ? { file, resourceLink: meta.resourceLink } : { file };
|
|
80
223
|
}, { defaultErrorCode: ErrorCode.UNKNOWN });
|
|
81
224
|
const results = [];
|
|
82
225
|
const failures = [];
|
|
226
|
+
const skipped = [];
|
|
83
227
|
const links = [];
|
|
84
228
|
for (const r of batch.results) {
|
|
85
229
|
if ('error' in r) {
|
|
86
230
|
failures.push({ path: r.path, error: r.error });
|
|
87
231
|
continue;
|
|
88
232
|
}
|
|
233
|
+
if ('skipped' in r.value) {
|
|
234
|
+
skipped.push(r.value.skipped);
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
89
237
|
results.push(r.value.file);
|
|
90
238
|
if (r.value.resourceLink)
|
|
91
239
|
links.push(r.value.resourceLink);
|
|
@@ -93,6 +241,7 @@ export const CREATE = defineTool({
|
|
|
93
241
|
const structured = {
|
|
94
242
|
files: results,
|
|
95
243
|
...(failures.length > 0 ? { failures } : {}),
|
|
244
|
+
...(skipped.length > 0 ? { skipped } : {}),
|
|
96
245
|
};
|
|
97
246
|
// No `text` on purpose. The one-line roster this used to build named the
|
|
98
247
|
// paths and dropped every per-file size, line count and error the caller
|
package/dist/tools/create.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.js","sourceRoot":"","sources":["../../src/tools/create.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAE9C,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EACL,QAAQ,EACR,WAAW,EACX,SAAS,EACT,iBAAiB,EACjB,YAAY,GACb,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE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AK,CAAC,IAAI,CAAC,CAAC;YAC3B,IAAI,CAAC,CAAC,KAAK,CAAC,YAAY;gBAAE,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QAC7D,CAAC;QAED,MAAM,UAAU,GAAG;YACjB,KAAK,EAAE,OAAO;YACd,GAAG,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC7C,CAAC;QACF,yEAAyE;QACzE,yEAAyE;QACzE,mEAAmE;QACnE,oEAAoE;QACpE,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACrB,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,cAAc,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;QAClF,CAAC;QAED,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,cAAc,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;IAChE,CAAC;IACD,QAAQ,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACnB,KAAK,EAAE,QAAQ;QACf,OAAO,EACL,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC;YACrB,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,IAAI,IAAI,EAAE,CAAC;YACrC,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ;KAC3C,CAAC;IACF,gBAAgB,EAAE,SAAS,CAAC,OAAO;CACpC,CAAC,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { basename, dirname } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { ErrorCode } from '../core/errors.js';\nimport { buildWrittenFileMeta } from '../core/file-uri.js';\nimport {\n FileKind,\n IsoDateTime,\n NonNegInt,\n PathFailureSchema,\n RequiredPath,\n} from '../core/schema.js';\nimport { getMaxTextFileSize } from '../core/util.js';\nimport { isTotalFailure, runOverPaths } from './batch.js';\nimport { defineTool } from './define.js';\n\nconst CreateFileItemSchema = z.strictObject({\n path: RequiredPath.describe('Absolute path where the file will be created'),\n content: z\n .string()\n .refine((val) => val.length <= getMaxTextFileSize(), {\n message: 'Content exceeds maximum allowed text file size',\n })\n .describe('Text content to write, verbatim.'),\n});\n\nconst CreateFileResultSchema = z.strictObject({\n path: z.string().describe('Resolved absolute path of the created file'),\n size: NonNegInt.describe('File size in bytes after writing'),\n lineCount: NonNegInt.describe('Number of lines in the written file'),\n mimeType: z.string().describe('Detected MIME type of the file'),\n kind: FileKind.describe('Broad file kind: text, binary, image, audio, or pdf'),\n resourceUri: z\n .string()\n .describe('Resource URI pointing to the created file content in the resource store'),\n created: IsoDateTime.describe('File creation timestamp (ISO 8601 UTC)'),\n modified: IsoDateTime.describe('File last-modification timestamp (ISO 8601 UTC)'),\n});\n\nconst CreateInputSchema = z.strictObject({\n files: z\n .array(CreateFileItemSchema)\n .min(1)\n .max(100)\n .describe('List of files to create (max 100); each entry requires path and content'),\n});\n\ntype CreateFailureItem = z.infer<typeof PathFailureSchema>;\n\nconst CreateOutputSchema = z.strictObject({\n files: z.array(CreateFileResultSchema).describe('Successfully created files'),\n failures: z\n .array(PathFailureSchema)\n .optional()\n .describe('Files that failed to create with per-file error details'),\n});\n\ntype CreateFileResult = z.infer<typeof CreateFileResultSchema>;\n\nexport const CREATE = defineTool({\n name: 'create',\n title: 'Create Files',\n description:\n 'Create one or more files (max 100), writing or overwriting content and creating parent directories as needed. ' +\n 'Pass files: [{ path, content }] — there is no single-path form. ' +\n 'Silently overwrites existing files — read first if you need to preserve existing content.',\n input: CreateInputSchema,\n output: CreateOutputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: false,\n },\n accessPaths: (args) => args.files.map((f) => f.path),\n run: async (args, ctx) => {\n const batch = await runOverPaths<\n { content: string },\n { file: CreateFileResult; resourceLink?: ContentBlock }\n >(\n { files: args.files },\n ctx,\n async ({ path, override }) => {\n const content = override?.content ?? '';\n\n await ctx.fs.mkdir(dirname(path), { recursive: true });\n\n const { validPath } = await ctx.fs.writeFile(path, content, {\n encoding: 'utf-8',\n signal: ctx.signal,\n });\n\n const { stats: fileStats } = await ctx.fs.stat(path, { signal: ctx.signal });\n const meta = buildWrittenFileMeta(validPath, content, ctx.resourceStore);\n\n const file: CreateFileResult = {\n path: validPath,\n size: meta.size,\n lineCount: meta.lineCount,\n mimeType: meta.mimeType,\n kind: meta.kind,\n resourceUri: meta.resourceUri,\n created: fileStats.birthtime.toISOString(),\n modified: fileStats.mtime.toISOString(),\n };\n\n return meta.resourceLink ? { file, resourceLink: meta.resourceLink } : { file };\n },\n { defaultErrorCode: ErrorCode.UNKNOWN },\n );\n\n const results: CreateFileResult[] = [];\n const failures: CreateFailureItem[] = [];\n const links: ContentBlock[] = [];\n for (const r of batch.results) {\n if ('error' in r) {\n failures.push({ path: r.path, error: r.error });\n continue;\n }\n results.push(r.value.file);\n if (r.value.resourceLink) links.push(r.value.resourceLink);\n }\n\n const structured = {\n files: results,\n ...(failures.length > 0 ? { failures } : {}),\n };\n // No `text` on purpose. The one-line roster this used to build named the\n // paths and dropped every per-file size, line count and error the caller\n // asked `create` for. Supplying no text makes this a data tool, so\n // `define.ts` renders the JSON and keeps it in `structuredContent`.\n if (links.length > 0) {\n return { structured, resources: links, isError: isTotalFailure(batch.summary) };\n }\n\n return { structured, isError: isTotalFailure(batch.summary) };\n },\n progress: (args) => ({\n label: 'Create',\n subject:\n args.files.length === 1\n ? basename(args.files[0]?.path ?? '')\n : `${String(args.files.length)} files`,\n }),\n defaultErrorCode: ErrorCode.UNKNOWN,\n});\n"]}
|
|
1
|
+
{"version":3,"file":"create.js","sourceRoot":"","sources":["../../src/tools/create.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE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protocol/server';\n\nimport { basename, dirname } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { processInParallel } from '../core/concurrency.js';\nimport { ErrorCode, formatUnknownErrorMessage, FsError, rethrowIfAborted } from '../core/errors.js';\nimport {\n buildFileResourceLink,\n buildFileResourceUri,\n buildWrittenFileMeta,\n type WrittenFileMeta,\n} from '../core/file-uri.js';\nimport { countFileLines, destExists, type Stats } from '../core/fs.js';\nimport {\n choiceInput,\n confirmKey,\n pendingRoundTrip,\n readAcceptedChoice,\n} from '../core/input-required.js';\nimport { detectMimeFromContent, MIME_SAMPLE_SIZE } from '../core/mime.js';\nimport {\n FileKind,\n IsoDateTime,\n NonNegInt,\n PathFailureSchema,\n RequiredPath,\n} from '../core/schema.js';\nimport { getMaxTextFileSize, PARALLEL_CONCURRENCY } from '../core/util.js';\nimport { isTotalFailure, runOverPaths } from './batch.js';\nimport { defineTool } from './define.js';\n\nconst EPOCH = new Date(0);\n\nconst CreateFileItemSchema = z.strictObject({\n path: RequiredPath.describe('Absolute path where the file will be created'),\n content: z\n .string()\n .refine((val) => val.length <= getMaxTextFileSize(), {\n message: 'Content exceeds maximum allowed text file size',\n })\n .describe('Text content to write, verbatim.'),\n append: z\n .boolean()\n .optional()\n .describe(\n 'Append the content to the end of the file instead of overwriting; creates the file if it does not exist',\n ),\n overwrite: z\n .boolean()\n .optional()\n .describe(\n 'Replace an existing file without asking the user; without it an existing file prompts for confirmation',\n ),\n});\n\nconst CreateFileResultSchema = z.strictObject({\n path: z.string().describe('Resolved absolute path of the created file'),\n size: NonNegInt.describe('File size in bytes after writing'),\n lineCount: NonNegInt.describe('Number of lines in the written file'),\n mimeType: z.string().describe('Detected MIME type of the file'),\n kind: FileKind.describe('Broad file kind: text, binary, image, audio, or pdf'),\n resourceUri: z\n .string()\n .optional()\n .describe(\n 'Resource URI pointing to the created file content in the resource store; omitted when the resulting file exceeds the text-size cap, which the store would reject',\n ),\n created: IsoDateTime.describe('File creation timestamp (ISO 8601 UTC)'),\n modified: IsoDateTime.describe('File last-modification timestamp (ISO 8601 UTC)'),\n});\n\nconst CreateInputSchema = z.strictObject({\n files: z\n .array(CreateFileItemSchema)\n .min(1)\n .max(100)\n .describe('List of files to create (max 100); each entry requires path and content'),\n});\n\ntype CreateFailureItem = z.infer<typeof PathFailureSchema>;\n\nconst CreateOutputSchema = z.strictObject({\n files: z.array(CreateFileResultSchema).describe('Successfully created files'),\n failures: z\n .array(PathFailureSchema)\n .optional()\n .describe('Files that failed to create with per-file error details'),\n skipped: z\n .array(z.string())\n .optional()\n .describe('Paths left untouched because the user chose Skip'),\n});\n\ntype CreateFileResult = z.infer<typeof CreateFileResultSchema>;\n\nexport const CREATE = defineTool({\n name: 'create',\n title: 'Create Files',\n description:\n 'Create one or more files (max 100), creating parent directories as needed. ' +\n 'Pass files: [{ path, content }] — there is no single-path form. ' +\n 'An existing file prompts the user to confirm the overwrite, so the call returns without writing ' +\n 'anything until that confirmation comes back; set overwrite: true on an entry to replace it without the prompt. ' +\n 'Set append: true on an entry to add to the end of an existing file (created if missing) instead of overwriting.',\n input: CreateInputSchema,\n output: CreateOutputSchema,\n annotations: {\n readOnlyHint: false,\n idempotentHint: false,\n destructiveHint: true,\n openWorldHint: false,\n },\n accessPaths: (args) => args.files.map((f) => f.path),\n run: async (args, ctx) => {\n // Phase 1 (no mutation): which entries would replace a file that exists\n // right now? Those need the user's word before anything is written (R14).\n // append never destroys, and overwrite: true is that word given up front.\n // A path that fails validation here is left for runOverPaths to report.\n // A file that appears between rounds needs no re-stat before the write:\n // the retry re-plans, and the grown pending set fails the R9 check.\n const { results: planned } = await processInParallel(\n args.files,\n async (entry) => {\n if (entry.append || entry.overwrite) return undefined;\n try {\n const validPath = await ctx.fs.pathGuard.validatePathForWrite(entry.path);\n return (await destExists(ctx.fs, validPath, 'create')) ? validPath : undefined;\n } catch (error) {\n rethrowIfAborted(error);\n return undefined;\n }\n },\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n const pendingByPath = new Map<string, string>();\n for (const { index, value } of planned) {\n const requested = args.files[index]?.path;\n if (value && requested) pendingByPath.set(requested, value);\n }\n const pendingSorted = [...new Set(pendingByPath.values())].sort();\n if (pendingSorted.length > 0) {\n // Round 1 returns input_required; a retry whose verified state does not\n // bind this overwrite set throws (R9) via `pendingRoundTrip`.\n const round = await pendingRoundTrip({\n op: 'create',\n pending: pendingSorted,\n requestState: ctx.requestState,\n clientCapabilities: ctx.clientCapabilities,\n buildInputs: (paths) =>\n paths.map((target, i) =>\n choiceInput(confirmKey(i), `\"${target}\" already exists. Overwrite it?`, [\n 'overwrite',\n 'skip',\n ]),\n ),\n });\n if (round !== undefined) return round;\n }\n\n const batch = await runOverPaths<\n { content: string; append?: boolean | undefined; overwrite?: boolean | undefined },\n { file: CreateFileResult; resourceLink?: ContentBlock } | { skipped: string }\n >(\n { files: args.files },\n ctx,\n async ({ path, override }) => {\n const content = override?.content ?? '';\n\n const pendingPath = pendingByPath.get(path);\n if (pendingPath !== undefined) {\n const key = confirmKey(pendingSorted.indexOf(pendingPath));\n const choice = readAcceptedChoice(ctx.inputResponses, key);\n if (choice === 'skip') return { skipped: path };\n if (choice !== 'overwrite') {\n throw new FsError(\n ErrorCode.CANCELLED,\n `create cancelled: overwrite of \"${path}\" was declined or missing`,\n path,\n );\n }\n }\n\n await ctx.fs.mkdir(dirname(path), { recursive: true });\n\n // Overwrite: file content == `content`, so content-derived meta is\n // exact and the atomic temp+rename write protects the existing mode.\n // Append: the resulting file is everything that was there plus\n // `content`, so size/created/modified come from a real post-append\n // stat, MIME from the resulting file's leading bytes, and the line\n // count streams the file — reading a multi-GB log back whole is the\n // round-trip append exists to avoid.\n let validPath: string;\n let meta: WrittenFileMeta;\n let created: string;\n let modified: string;\n if (override?.append) {\n const appended = await ctx.fs.appendFile(path, content, {\n encoding: 'utf-8',\n signal: ctx.signal,\n });\n validPath = appended.validPath;\n // The append is the commit point: the bytes are on disk, so\n // everything below is best-effort RESULT METADATA, not part of the\n // write. It runs unwired to ctx.signal, and a metadata failure\n // degrades the result instead of failing it — either would report\n // the append as failed and a client retry would append twice. The\n // stat covers the committed validPath, never the input path: a\n // symlink there could have been swapped between write and stat,\n // and the result must describe the file the bytes landed in.\n let stats: Stats | undefined;\n let mimeType: string;\n let kind: FileKind;\n let lineCount = 0;\n try {\n stats = (await ctx.fs.stat(appended.validPath)).stats;\n // Sniff the resulting file's leading bytes, not the appended\n // chunk: text appended to a binary file is still a binary file.\n const sample = await ctx.fs.readLeadingSample(appended.validPath, MIME_SAMPLE_SIZE);\n const mimeInfo = detectMimeFromContent(appended.validPath, sample);\n mimeType = mimeInfo.mimeType;\n kind = mimeInfo.kind;\n lineCount = await countFileLines(appended.validPath);\n } catch (error) {\n ctx.log?.(\n 'warning',\n `create append: result metadata degraded for ${appended.validPath}: ${formatUnknownErrorMessage(error)}`,\n 'create',\n );\n // A POSIX mode-0222 file appends fine but cannot be opened 'r';\n // fall back to the chunk for MIME (an approximation) and report\n // the line count as unknown-as-zero rather than fail the append.\n const mimeInfo = detectMimeFromContent(appended.validPath, content);\n mimeType = mimeInfo.mimeType;\n kind = mimeInfo.kind;\n }\n // The resource store serves this URI via readRaw, which rejects\n // files over the text-size cap with TOO_LARGE — never advertise a\n // link the store deterministically cannot serve. A failed stat\n // leaves the size unknown, so nothing is advertised either.\n const servable = stats !== undefined && stats.size <= getMaxTextFileSize();\n const size = stats?.size ?? 0;\n meta = {\n size,\n lineCount,\n mimeType,\n kind,\n resourceUri: servable ? buildFileResourceUri(appended.validPath) : undefined,\n resourceLink:\n servable && ctx.resourceStore\n ? buildFileResourceLink(appended.validPath, mimeType, size)\n : undefined,\n };\n created = (stats?.birthtime ?? EPOCH).toISOString();\n modified = (stats?.mtime ?? EPOCH).toISOString();\n } else {\n const written = await ctx.fs.writeFile(path, content, {\n encoding: 'utf-8',\n signal: ctx.signal,\n });\n validPath = written.validPath;\n const fileStats = (await ctx.fs.stat(path, { signal: ctx.signal })).stats;\n created = fileStats.birthtime.toISOString();\n modified = fileStats.mtime.toISOString();\n meta = buildWrittenFileMeta(written.validPath, content, ctx.resourceStore);\n }\n\n const file: CreateFileResult = {\n path: validPath,\n size: meta.size,\n lineCount: meta.lineCount,\n mimeType: meta.mimeType,\n kind: meta.kind,\n resourceUri: meta.resourceUri,\n created,\n modified,\n };\n\n return meta.resourceLink ? { file, resourceLink: meta.resourceLink } : { file };\n },\n { defaultErrorCode: ErrorCode.UNKNOWN },\n );\n\n const results: CreateFileResult[] = [];\n const failures: CreateFailureItem[] = [];\n const skipped: string[] = [];\n const links: ContentBlock[] = [];\n for (const r of batch.results) {\n if ('error' in r) {\n failures.push({ path: r.path, error: r.error });\n continue;\n }\n if ('skipped' in r.value) {\n skipped.push(r.value.skipped);\n continue;\n }\n results.push(r.value.file);\n if (r.value.resourceLink) links.push(r.value.resourceLink);\n }\n\n const structured = {\n files: results,\n ...(failures.length > 0 ? { failures } : {}),\n ...(skipped.length > 0 ? { skipped } : {}),\n };\n // No `text` on purpose. The one-line roster this used to build named the\n // paths and dropped every per-file size, line count and error the caller\n // asked `create` for. Supplying no text makes this a data tool, so\n // `define.ts` renders the JSON and keeps it in `structuredContent`.\n if (links.length > 0) {\n return { structured, resources: links, isError: isTotalFailure(batch.summary) };\n }\n\n return { structured, isError: isTotalFailure(batch.summary) };\n },\n progress: (args) => ({\n label: 'Create',\n subject:\n args.files.length === 1\n ? basename(args.files[0]?.path ?? '')\n : `${String(args.files.length)} files`,\n }),\n defaultErrorCode: ErrorCode.UNKNOWN,\n});\n"]}
|