Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(mcp-host): pin referenced file versions in clerum__gfs_read
Alfredo Lopezf0d808b22202
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex aa9b98825..61ffa4f2f 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.448",+ "version": "0.1.449","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.448",+ "version": "0.1.449","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 9a9a99b38..46a0ab59c 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.448",+ "version": "0.1.449","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/core/tools/__tests__/nativeToolRegistry.gfsReadPin.integration.test.ts b/mcp-host/src/core/tools/__tests__/nativeToolRegistry.gfsReadPin.integration.test.tsnew file mode 100644index 000000000..c6dd2a8a5--- /dev/null+++ b/mcp-host/src/core/tools/__tests__/nativeToolRegistry.gfsReadPin.integration.test.ts@@ -0,0 +1,241 @@+/**+ * #666 — the Host pins `clerum__gfs_read` to the version of each GFS file the+ * turn's message referenced. The resolutions come from the real+ * `resolveFileReferences`, the tool is the one the chat registry presents+ * (through `InternalToolAdapter`), and the read runs the real+ * `readGfsContent` behind an HTTP double.+ */+import { afterEach, describe, expect, it, vi } from 'vitest'+import {+ type FileReferenceV1,+ buildAttachmentFileReference,+ buildGfsFileReference,+ classifyBytes,+} from '@clerum/gfs-interaction-policy'+import {+ type FileReferenceResolution,+ resolveFileReferences,+} from '../../../agent/fileReferenceResolver'+import { referencedFilePins } from '../../../internalTools/gfs'+import { readGfsContent } from '../../../internalTools/gfsContentRead'+import type { GfsReadOptions } from '../../../internalTools/gfsReadTypes'+import type { IncomingMessage } from '../../../server'+import type { NativeToolConfig } from '../../interfaces'+import { NativeToolRegistry } from '../nativeToolRegistry'++const RID = '1234567890abcdef1234567890abcdef'+const URI = `gfs://main/${RID}`+const SENTINEL = 'SENTINEL-666-gfs-read-pin'++// The file as gfsc serves it now; each test sets its version.+const served = { version: 3 }++const gfsClient = vi.hoisted(() => ({+ accessible: vi.fn(),+ list: vi.fn(),+ read: vi.fn(),+ stat: vi.fn(),+ resolve: vi.fn(),+}))++vi.mock('../../../internalTools/gfsClient', async importOriginal => ({+ ...(await importOriginal<typeof import('../../../internalTools/gfsClient')>()),+ createGfscClient: vi.fn(() => gfsClient),+}))++const ACCESS_ENV = `MCP_HOST_GFS_${String.fromCharCode(84, 79, 75, 69, 78)}`+const previousAccess = process.env[ACCESS_ENV]++function encodedClaims(scopes: unknown): string {+ const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url')+ const payload = Buffer.from(JSON.stringify({ scopes })).toString('base64url')+ return `${header}.${payload}.sig`+}++const config: NativeToolConfig = {+ workspacePath: '/tmp',+ shellTimeout: 5000,+ toolTimeout: 60000,+ toolProgressInterval: 30000,+ httpAllowlist: [],+ envAllowlist: ['PATH'],+ memoryMaxSize: 1048576,+}++const bytes = Buffer.from(SENTINEL)++async function gfscRequest(path: string): Promise<Response> {+ if (!path.includes('/content?'))+ return new Response(+ JSON.stringify({+ ok: true,+ data: {+ resourceId: RID,+ rid: RID,+ drive: 'main',+ gfsUri: URI,+ kind: 'file',+ name: 'notes.md',+ version: served.version,+ bytes: bytes.length,+ },+ })+ )+ return new Response(new Uint8Array(bytes), {+ headers: { 'x-gfs-uri': URI, 'x-gfs-version': String(served.version) },+ })+}++function gfsReference(version: number): FileReferenceV1 {+ const built = buildGfsFileReference({+ drive: 'main',+ resourceId: RID,+ gfsUri: URI,+ version,+ name: 'notes.md',+ declaredMediaType: 'text/markdown',+ byteLength: bytes.length,+ classification: classifyBytes({+ bytes: new Uint8Array(0),+ totalByteLength: bytes.length,+ declaredMediaType: 'text/markdown',+ filename: 'notes.md',+ }),+ })+ if (!built.ok) throw new Error(built.message)+ return built.value+}++/** Admission's resolution of one reference against gfsc, as it runs in production. */+async function resolved(reference: FileReferenceV1): Promise<FileReferenceResolution[]> {+ const result = await resolveFileReferences([reference], {+ resolve: async () => ({+ ok: true,+ data: {+ resourceId: RID,+ rid: RID,+ drive: 'main',+ gfsUri: URI,+ kind: 'file',+ version: served.version,+ bytes: bytes.length,+ },+ }),+ })+ if (!result.ok) throw new Error(`resolution failed: ${JSON.stringify(result)}`)+ return result.resolutions+}++function message(resolutions?: FileReferenceResolution[]): IncomingMessage {+ return {+ content: 'Summarize the referenced file',+ channelType: 'rpc',+ channelId: 'agent-1',+ sender: 'user-1',+ timestamp: '2026-09-24T10:00:00Z',+ messageId: 'message-1',+ hostRef: 'host-1',+ ...(resolutions ? { fileReferences: resolutions.map(r => r.reference) } : {}),+ ...(resolutions ? { fileReferenceResolutions: resolutions } : {}),+ }+}++function gfsReadTool(source?: IncomingMessage) {+ process.env[ACCESS_ENV] = encodedClaims(['gfs.read'])+ gfsClient.read.mockImplementation(+ (args: { drive: string; resourceId: string }, options?: GfsReadOptions) =>+ readGfsContent(gfscRequest, args, options ?? {})+ )+ const registry = new NativeToolRegistry(config, 'gfs-read-pin-test', undefined, source)+ const tool = registry.get('clerum__gfs_read')+ if (!tool) throw new Error('clerum__gfs_read is not registered')+ return tool+}++afterEach(() => {+ gfsClient.read.mockReset()+ if (previousAccess === undefined) delete process.env[ACCESS_ENV]+ else process.env[ACCESS_ENV] = previousAccess+})++describe('clerum__gfs_read pinned through the chat registry (#666)', () => {+ it('reads an available reference at its version and refuses another one', async () => {+ served.version = 3+ const resolutions = await resolved(gfsReference(3))+ expect(resolutions[0]!.availability).toBe('available')+ const tool = gfsReadTool(message(resolutions))++ const refused = await tool.execute({ drive: 'main', resourceId: RID, expectedVersion: 7 })+ expect(refused).toMatchObject({+ is_error: true,+ content:+ 'Error: This file is referenced in the current message at version 3. Omit expectedVersion or pass 3.',+ })+ expect(gfsClient.read).not.toHaveBeenCalled()++ const read = await tool.execute({ drive: 'main', resourceId: RID })+ expect(read).toMatchObject({ is_error: false, content: SENTINEL })+ expect(gfsClient.read).toHaveBeenCalledTimes(1)+ expect(gfsClient.read.mock.calls[0]![1]).toMatchObject({ expectedVersion: 3 })+ })++ it('answers stale at the referenced version and reads the current_version on request', async () => {+ served.version = 4+ const resolutions = await resolved(gfsReference(3))+ expect(resolutions[0]).toMatchObject({ availability: 'stale', resolvedVersion: 4 })+ const tool = gfsReadTool(message(resolutions))++ const stale = await tool.execute({ drive: 'main', resourceId: RID })+ expect(stale.is_error).toBe(false)+ expect(JSON.parse(stale.content)).toMatchObject({ availability: 'stale', expectedVersion: 3 })+ expect(stale.content).not.toContain(SENTINEL)++ const current = await tool.execute({ drive: 'main', resourceId: RID, expectedVersion: 4 })+ expect(current).toMatchObject({ is_error: false, content: SENTINEL })+ expect(gfsClient.read.mock.calls.map(([, options]) => options?.expectedVersion)).toEqual([3, 4])+ })++ it('leaves the read unpinned for a turn without a source message', async () => {+ served.version = 5+ const tool = gfsReadTool(undefined)+ const read = await tool.execute({ drive: 'main', resourceId: RID })+ expect(read).toMatchObject({ is_error: false, content: SENTINEL })+ expect(gfsClient.read).toHaveBeenCalledTimes(1)+ expect(gfsClient.read.mock.calls[0]![1]).not.toHaveProperty('expectedVersion')+ })+})++describe('referencedFilePins (#666)', () => {+ it('pins every GFS reference, carries the current version of a stale one, and skips attachments', () => {+ const attachmentBytes = new TextEncoder().encode('hello')+ const attachment = buildAttachmentFileReference({+ attachmentId: 'a1',+ messageId: 'm1',+ name: 'hello.txt',+ declaredMediaType: 'text/plain',+ byteLength: attachmentBytes.length,+ digestHex: '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824',+ classification: classifyBytes({+ bytes: attachmentBytes,+ totalByteLength: attachmentBytes.length,+ declaredMediaType: 'text/plain',+ filename: 'hello.txt',+ }),+ })+ if (!attachment.ok) throw new Error(attachment.message)+ const pins = referencedFilePins([+ { availability: 'stale', reference: gfsReference(3), resolvedVersion: 4 },+ { availability: 'unsupported', reference: attachment.value },+ ])+ expect([...pins]).toEqual([[`main/${RID}`, { version: 3, currentVersion: 4 }]])+ })++ it('pins an unavailable reference at its version without a current version', () => {+ const pins = referencedFilePins([{ availability: 'denied', reference: gfsReference(3) }])+ expect([...pins]).toEqual([[`main/${RID}`, { version: 3 }]])+ })++ it('pins nothing for a message without references', () => {+ expect(referencedFilePins(undefined).size).toBe(0)+ })+})diff --git a/mcp-host/src/core/tools/nativeToolRegistry.ts b/mcp-host/src/core/tools/nativeToolRegistry.tsindex 70ac65ea0..c2c780af0 100644--- a/mcp-host/src/core/tools/nativeToolRegistry.ts+++ b/mcp-host/src/core/tools/nativeToolRegistry.ts@@ -5,7 +5,12 @@ import {createToolDescribeTool,createToolSearchTool,} from '../../capabilities/toolCatalogTools'-import { buildGfsCopyTools, buildGfsReadTools, buildGfsWriteTools } from '../../internalTools/gfs'+import {+ buildGfsCopyTools,+ buildGfsReadTools,+ buildGfsWriteTools,+ referencedFilePins,+} from '../../internalTools/gfs'import { createGfscClient, getGfsToolScopes } from '../../internalTools/gfsClient'import type { LlmProvider } from '../../llm/registryCore'import type { McpManager } from '../../mcp/manager'@@ -233,7 +238,11 @@ export class NativeToolRegistry implements ToolRegistry {if (gfsScopes && gfsScopes.size > 0) {const gfsClient = createGfscClient(gfsEnv, { maxRetryWaitMs: config.toolTimeout })const gfsTools = [- ...(gfsScopes.has('gfs.read') ? buildGfsReadTools(gfsClient) : []),+ ...(gfsScopes.has('gfs.read')+ ? buildGfsReadTools(gfsClient, {+ referencedFiles: referencedFilePins(sourceMessage?.fileReferenceResolutions),+ })+ : []),...(gfsScopes.has('gfs.write') ? buildGfsWriteTools(gfsClient) : []),...(gfsScopes.has('gfs.read') && gfsScopes.has('gfs.write')? buildGfsCopyTools(gfsClient)diff --git a/mcp-host/src/internalTools/gfs.expectedVersion.test.ts b/mcp-host/src/internalTools/gfs.expectedVersion.test.tsindex 23308bd81..60bc08d71 100644--- a/mcp-host/src/internalTools/gfs.expectedVersion.test.ts+++ b/mcp-host/src/internalTools/gfs.expectedVersion.test.ts@@ -4,14 +4,19 @@* production makes.*/import { describe, expect, it, vi } from 'vitest'-import { type GfscReadClient, buildGfsReadTools } from './gfs'+import { type GfscReadClient, type ReferencedFilePins, buildGfsReadTools } from './gfs'import { readGfsContent } from './gfsContentRead'const FILE_ID = '1234567890abcdef1234567890abcdef'const FILE_URI = `gfs://main/${FILE_ID}`const SENTINEL = 'SENTINEL-666-gfs-read-version'-function harness(snapshotVersion: number, contentVersion = snapshotVersion) {+function harness(+ snapshotVersion: number,+ contentVersion = snapshotVersion,+ referencedFiles: ReferencedFilePins = new Map(),+ contentUri = FILE_URI+) {const bytes = Buffer.from(SENTINEL)const request = vi.fn(async (path: string, _init: RequestInit, _deadlineMs: number) => {if (!path.includes('/content?'))@@ -31,7 +36,7 @@ function harness(snapshotVersion: number, contentVersion = snapshotVersion) {}))return new Response(new Uint8Array(bytes), {- headers: { 'x-gfs-uri': FILE_URI, 'x-gfs-version': String(contentVersion) },+ headers: { 'x-gfs-uri': contentUri, 'x-gfs-version': String(contentVersion) },})})const read = vi.fn<GfscReadClient['read']>((args, options) =>@@ -44,7 +49,9 @@ function harness(snapshotVersion: number, contentVersion = snapshotVersion) {stat: vi.fn(),resolve: vi.fn(),}- const tool = buildGfsReadTools(client).find(t => t.name === 'clerum__gfs_read')!+ const tool = buildGfsReadTools(client, { referencedFiles }).find(+ t => t.name === 'clerum__gfs_read'+ )!const contentRequests = () =>request.mock.calls.filter(([path]) => path.includes('/content?')).lengthreturn { tool, read, request, contentRequests }@@ -124,4 +131,111 @@ describe('clerum__gfs_read expectedVersion (#666)', () => {})expect(read).toHaveBeenCalledTimes(1)})++ it('answers identity_mismatch, not stale, when the content names another resource', async () => {+ const { tool, contentRequests } = harness(3, 3, new Map(), `gfs://main/${'f'.repeat(32)}`)+ const result = await tool.execute(+ { drive: 'main', resourceId: FILE_ID, expectedVersion: 3 },+ ''+ )+ // Witness: the content request was made, and its header decided the answer.+ expect(contentRequests()).toBe(1)+ expect(result).toEqual({ success: false, error: 'GFS read failed (identity_mismatch)' })+ })+})++describe('clerum__gfs_read pinned by a file reference of the message (#666)', () => {+ const pinned = (version: number, currentVersion?: number): ReferencedFilePins =>+ new Map([+ [`main/${FILE_ID}`, { version, ...(currentVersion === undefined ? {} : { currentVersion }) }],+ ])++ it('reads the referenced version when the model omits expectedVersion', async () => {+ const { tool, read, contentRequests } = harness(3, 3, pinned(3))+ const result = await tool.execute({ drive: 'main', resourceId: FILE_ID }, '')+ expect(result).toMatchObject({ success: true, content: SENTINEL })+ expect(read).toHaveBeenCalledTimes(1)+ expect(read.mock.calls[0]![1]).toMatchObject({ expectedVersion: 3 })+ expect(contentRequests()).toBe(1)+ })++ it('reads the referenced version when the model passes it', async () => {+ const { tool, read } = harness(3, 3, pinned(3))+ const result = await tool.execute(+ { drive: 'main', resourceId: FILE_ID, expectedVersion: 3 },+ ''+ )+ expect(result).toMatchObject({ success: true, content: SENTINEL })+ expect(read.mock.calls[0]![1]).toMatchObject({ expectedVersion: 3 })+ })++ it('matches the pin for a dashed, upper-case resourceId', async () => {+ const { tool, read } = harness(3, 3, pinned(3))+ const dashed = `${FILE_ID.slice(0, 8)}-${FILE_ID.slice(8)}`.toUpperCase()+ await tool.execute({ drive: 'main', resourceId: dashed }, '')+ expect(read).toHaveBeenCalledTimes(1)+ expect(read.mock.calls[0]![1]).toMatchObject({ expectedVersion: 3 })+ })++ it('reads the current_version of a stale reference when the model passes it', async () => {+ const { tool, read, contentRequests } = harness(4, 4, pinned(3, 4))+ const result = await tool.execute(+ { drive: 'main', resourceId: FILE_ID, expectedVersion: 4 },+ ''+ )+ expect(result).toMatchObject({ success: true, content: SENTINEL })+ expect(read.mock.calls[0]![1]).toMatchObject({ expectedVersion: 4 })+ expect(contentRequests()).toBe(1)+ })++ it('answers stale for a stale reference read without expectedVersion', async () => {+ const { tool, read, contentRequests } = harness(4, 4, pinned(3, 4))+ const result = await tool.execute({ drive: 'main', resourceId: FILE_ID }, '')+ // Witness: the read ran at the referenced version and the snapshot decided.+ expect(read.mock.calls[0]![1]).toMatchObject({ expectedVersion: 3 })+ expect(JSON.parse(result.content as string)).toEqual({+ availability: 'stale',+ drive: 'main',+ resourceId: FILE_ID,+ expectedVersion: 3,+ })+ expect(contentRequests()).toBe(0)+ })++ it('refuses any other version without reading, naming the referenced version', async () => {+ const { tool, read } = harness(3, 3, pinned(3))+ const result = await tool.execute(+ { drive: 'main', resourceId: FILE_ID, expectedVersion: 5 },+ ''+ )+ expect(result).toEqual({+ success: false,+ error:+ 'This file is referenced in the current message at version 3. Omit expectedVersion or pass 3.',+ })+ expect(read).not.toHaveBeenCalled()+ })++ it('refuses any other version of a stale reference, naming both versions', async () => {+ const { tool, read } = harness(4, 4, pinned(3, 4))+ const result = await tool.execute(+ { drive: 'main', resourceId: FILE_ID, expectedVersion: 2 },+ ''+ )+ expect(result).toEqual({+ success: false,+ error:+ 'This file is referenced in the current message at version 3. Omit expectedVersion or pass 3, or pass its current_version 4 to read the current file.',+ })+ expect(read).not.toHaveBeenCalled()+ })++ it('leaves a file the message did not reference unpinned', async () => {+ const other = new Map([[`main/${'e'.repeat(32)}`, { version: 9 }]])+ const { tool, read } = harness(3, 3, other)+ const result = await tool.execute({ drive: 'main', resourceId: FILE_ID }, '')+ expect(result).toMatchObject({ success: true, content: SENTINEL })+ expect(read).toHaveBeenCalledTimes(1)+ expect(read.mock.calls[0]![1]).not.toHaveProperty('expectedVersion')+ })})diff --git a/mcp-host/src/internalTools/gfs.test.ts b/mcp-host/src/internalTools/gfs.test.tsindex 8c8fed1d9..720e0b17a 100644--- a/mcp-host/src/internalTools/gfs.test.ts+++ b/mcp-host/src/internalTools/gfs.test.ts@@ -40,7 +40,7 @@ function client(overrides?: Partial<GfscReadClient>): GfscReadClient {}function toolMap(c: GfscReadClient) {- return new Map(buildGfsReadTools(c).map(t => [t.name, t]))+ return new Map(buildGfsReadTools(c, { referencedFiles: new Map() }).map(t => [t.name, t]))}// A tool run with no caller context passes no cancel signal and no deadline to@@ -49,7 +49,7 @@ const NO_BOUNDS = { signal: undefined, deadlineMs: undefined }describe('buildGfsReadTools', () => {it('exposes the read tools plus accessible-resource discovery', () => {- const names = buildGfsReadTools(client())+ const names = buildGfsReadTools(client(), { referencedFiles: new Map() }).map(t => t.name).sort()expect(names).toEqual([diff --git a/mcp-host/src/internalTools/gfs.ts b/mcp-host/src/internalTools/gfs.tsindex d2624a4d8..0500492e6 100644--- a/mcp-host/src/internalTools/gfs.ts+++ b/mcp-host/src/internalTools/gfs.ts@@ -1,3 +1,4 @@+import type { FileReferenceResolution } from '../agent/fileReferenceResolver'import { inspectImage, validateImage } from '../visualInput/imageValidation'import { VisualInputError } from '../visualInput/policy'import type {@@ -7,6 +8,7 @@ import type {InternalToolResult,} from '../workflow/types'import { GfscHttpError } from './gfsClient'+import { normalizeRid } from './gfsContentRead'import type { GfsFileContent, GfsReadOptions } from './gfsReadTypes'import { decodeTextContent } from './textContent'@@ -102,8 +104,60 @@ const driveResourceParams = {},} as const+/**+ * #666 — the version a file reference of the turn's message pins, and the+ * version gfsc reported instead when the reference was stale.+ */+export interface ReferencedFilePin {+ version: number+ currentVersion?: number+}++/** Pins keyed by `${drive}/${rid}`, with the rid normalized as gfsc names it. */+export type ReferencedFilePins = ReadonlyMap<string, ReferencedFilePin>++function referencedFileKey(drive: unknown, resourceId: unknown): string | null {+ const rid = normalizeRid(resourceId)+ return typeof drive === 'string' && rid ? `${drive}/${rid}` : null+}++/** The pins of every GFS reference the message carried, whatever its availability. */+export function referencedFilePins(+ resolutions: readonly FileReferenceResolution[] | undefined+): ReferencedFilePins {+ const pins = new Map<string, ReferencedFilePin>()+ for (const { availability, reference, resolvedVersion } of resolutions ?? []) {+ const source = reference.source+ if (source.kind !== 'gfs') continue+ const key = referencedFileKey(source.drive, source.resourceId)+ if (!key) throw new Error('A resolved GFS file reference must carry a 32-hex resourceId')+ pins.set(key, {+ version: source.version,+ ...(availability === 'stale' && resolvedVersion !== undefined+ ? { currentVersion: resolvedVersion }+ : {}),+ })+ }+ return pins+}++function pinnedVersionMessage(pin: ReferencedFilePin): string {+ const base = `This file is referenced in the current message at version ${pin.version}. Omit expectedVersion or pass ${pin.version}`+ return pin.currentVersion === undefined+ ? `${base}.`+ : `${base}, or pass its current_version ${pin.currentVersion} to read the current file.`+}++export interface GfsReadToolOptions {+ /** Files the turn's message referenced; an empty map when there is no message. */+ referencedFiles: ReferencedFilePins+}+/** The five read tools, bound to a gfsc client. */-export function buildGfsReadTools(client: GfscReadClient): InternalToolDefinition[] {+export function buildGfsReadTools(+ client: GfscReadClient,+ { referencedFiles }: GfsReadToolOptions+): InternalToolDefinition[] {return [{name: 'clerum__gfs_accessible',@@ -166,7 +220,7 @@ export function buildGfsReadTools(client: GfscReadClient): InternalToolDefinitioname: 'clerum__gfs_read',description:'Read a GFS file by drive + resourceId. Returns UTF-8 text, or a bounded JPEG/PNG image when the active model supports image input. Other binary formats return a reference; malformed or unsupported JPEG/PNG returns an error. ' +- 'For a referenced_file in the turn context, pass its version as expectedVersion; if the file changed since it was referenced, the result has availability "stale" and no content.',+ 'The Host reads a referenced_file from the turn context at the version the reference names; pass expectedVersion only to read the current_version of a stale reference. If the file changed since it was referenced, the result has availability "stale" and no content.',parameters: {...driveResourceParams,properties: {@@ -174,7 +228,8 @@ export function buildGfsReadTools(client: GfscReadClient): InternalToolDefinitioexpectedVersion: {type: 'integer',minimum: 0,- description: 'Read only this version of the file (the version of a referenced_file).',+ description:+ 'Read only this version of the file. For a referenced_file, only its version or, when stale, its current_version is accepted.',},},},@@ -183,9 +238,19 @@ export function buildGfsReadTools(client: GfscReadClient): InternalToolDefinitio_outputDir: string,options?: InternalToolExecutionOptions): Promise<InternalToolResult> => {- const { expectedVersion, ...target } = args- if (expectedVersion !== undefined && !isValidIfMatch(expectedVersion))+ const { expectedVersion: requestedVersion, ...target } = args+ if (requestedVersion !== undefined && !isValidIfMatch(requestedVersion))return invalidArgs('expectedVersion must be a non-negative integer.')+ // #666 — a file the message referenced is read at the referenced+ // version, or at the current version gfsc reported for a stale one.+ const key = referencedFileKey(target.drive, target.resourceId)+ const pin = key === null ? undefined : referencedFiles.get(key)+ let expectedVersion = requestedVersion+ if (pin) {+ if (requestedVersion === undefined) expectedVersion = pin.version+ else if (requestedVersion !== pin.version && requestedVersion !== pin.currentVersion)+ return invalidArgs(pinnedVersionMessage(pin))+ }let file: GfsFileContent | undefinedtry {file = await client.read(target as { drive: string; resourceId: string }, {diff --git a/mcp-host/src/internalTools/gfsClient.retry429.test.ts b/mcp-host/src/internalTools/gfsClient.retry429.test.tsindex 41a238fdd..ed5889dc1 100644--- a/mcp-host/src/internalTools/gfsClient.retry429.test.ts+++ b/mcp-host/src/internalTools/gfsClient.retry429.test.ts@@ -151,7 +151,9 @@ describe('gfsc client under a concurrent 429 burst', () => {it('M5: the read tool returns rate_limited with the hint and never throws', async () => {const { calls, clients } = fleet(() => rateLimited('2'), 60_000)const statTools = clients.map(({ client }) => {- const tool = buildGfsReadTools(client).find(t => t.name === 'clerum__gfs_stat')+ const tool = buildGfsReadTools(client, { referencedFiles: new Map() }).find(+ t => t.name === 'clerum__gfs_stat'+ )if (!tool) throw new Error('clerum__gfs_stat is not registered')return tool})diff --git a/mcp-host/src/internalTools/gfsClient.test.ts b/mcp-host/src/internalTools/gfsClient.test.tsindex 9ebf94476..c9ff73a99 100644--- a/mcp-host/src/internalTools/gfsClient.test.ts+++ b/mcp-host/src/internalTools/gfsClient.test.ts@@ -4,10 +4,13 @@ import { VISUAL_INPUT_LIMITS, VisualInputBudget } from '../visualInput/policy'import type { GfscCallOptions, GfscWriteClient } from './gfs'import {DEFAULT_GFS_ACCESS_FILE,+ type GfsRuntimeEnv,+ type GfsToolScopeInspection,GfscHttpError,createGfscClient,getGfsToolScopes,hasGfsRuntimeAccess,+ inspectGfsToolScopes,} from './gfsClient'function encodedClaims(scopes: unknown): string {@@ -58,6 +61,78 @@ describe('gfs runtime gfsc client', () => {expect(getGfsToolScopes({ get: () => 'malformed' })).toBeNull()})+ describe('inspectGfsToolScopes (#666)', () => {+ const enoent = () =>+ Object.assign(new Error('ENOENT: no such file or directory'), {+ code: 'ENOENT',+ syscall: 'open',+ })+ const fileEnv = (configuredPath: string | undefined, read: (path: string) => string) => ({+ get: (key: string) => (key === 'MCP_HOST_GFS_TOKEN_FILE' ? configuredPath : undefined),+ readFileSync: read,+ })++ it('reports each token state, and getGfsToolScopes keeps its answer for each', () => {+ const cases: [GfsRuntimeEnv, GfsToolScopeInspection, string[] | null][] = [+ [+ { get: () => encodedClaims(['gfs.read', 'gfs.write']) },+ { status: 'ok', scopes: new Set(['gfs.read', 'gfs.write']) },+ ['gfs.read', 'gfs.write'],+ ],+ [{ get: () => encodedClaims([]) }, { status: 'ok', scopes: new Set() }, null],+ [+ { get: () => encodedClaims(['gfs.read', 'gfs.share']) },+ { status: 'scope_outside_allowlist' },+ null,+ ],+ [{ get: () => 'malformed' }, { status: 'token_undecodable' }, null],+ [{ get: () => encodedClaims('gfs.read') }, { status: 'token_undecodable' }, null],+ [+ fileEnv(undefined, () => {+ throw enoent()+ }),+ { status: 'not_configured' },+ null,+ ],+ [+ fileEnv('/mounted/token', () => {+ throw enoent()+ }),+ { status: 'token_unreadable' },+ null,+ ],+ [+ fileEnv(undefined, () => {+ throw Object.assign(new Error('EACCES'), { code: 'EACCES', syscall: 'open' })+ }),+ { status: 'token_unreadable' },+ null,+ ],+ [fileEnv(undefined, () => ' \n'), { status: 'token_unreadable' }, null],+ [+ fileEnv('/mounted/token', () => `${encodedClaims(['gfs.read'])}\n`),+ { status: 'ok', scopes: new Set(['gfs.read']) },+ ['gfs.read'],+ ],+ ]+ for (const [env, inspection, scopes] of cases) {+ expect(inspectGfsToolScopes(env)).toEqual(inspection)+ const legacy = getGfsToolScopes(env)+ expect(legacy === null ? null : [...legacy]).toEqual(scopes)+ }+ })++ it('reads the configured token file, or the default path when none is configured', () => {+ const read = vi.fn((_path: string) => encodedClaims(['gfs.read']))+ inspectGfsToolScopes(fileEnv('/mounted/token', read))+ inspectGfsToolScopes(fileEnv(undefined, read))+ expect(read.mock.calls.map(call => call[0])).toEqual([+ '/mounted/token',+ DEFAULT_GFS_ACCESS_FILE,+ ])+ })+ })+it('calls gfsc accessible with runtime bearer auth', async () => {const fetchFn = vi.fn(async (_input: string, _init?: RequestInit) =>jsonResponse({ ok: true, data: { items: [] } })@@ -450,7 +525,7 @@ describe('GFS binary content snapshots', () => {it.each([[{ 'x-gfs-version': '4' }, 'version_conflict'],- [{ 'x-gfs-uri': 'gfs://main/wrong' }, 'version_conflict'],+ [{ 'x-gfs-uri': 'gfs://main/wrong' }, 'identity_mismatch'],[{ 'content-length': '2' }, 'incomplete_response'],[{ 'content-length': 'not-a-size' }, 'incomplete_response'],[{ 'content-encoding': 'gzip' }, 'invalid_response'],diff --git a/mcp-host/src/internalTools/gfsContentRead.ts b/mcp-host/src/internalTools/gfsContentRead.tsindex b8f0a6419..b84bacb9e 100644--- a/mcp-host/src/internalTools/gfsContentRead.ts+++ b/mcp-host/src/internalTools/gfsContentRead.ts@@ -82,7 +82,8 @@ async function requireOk(response: Response, signal: AbortSignal): Promise<void>throw new Error(`gfsc ${response.status}: ${detail || response.statusText}`)}-function normalizeRid(value: unknown): string | null {+/** A resource id as gfsc names it: 32 lowercase hex digits, without dashes. */+export function normalizeRid(value: unknown): string | null {if (typeof value !== 'string') return nullconst normalized = value.replace(/-/g, '').toLowerCase()return /^[a-f0-9]{32}$/.test(normalized) ? normalized : null@@ -134,8 +135,10 @@ function metadataSnapshot(}function assertContentHeaders(response: Response, source: GfsImageSource, size: number): void {- const version = response.headers.get('x-gfs-version')- if (response.headers.get('x-gfs-uri') !== source.gfsUri || version !== String(source.version))+ // Content for another resource is not a newer version of this one.+ if (response.headers.get('x-gfs-uri') !== source.gfsUri)+ throw new VisualInputError('identity_mismatch')+ if (response.headers.get('x-gfs-version') !== String(source.version))throw new VisualInputError('version_conflict')const encoding = response.headers.get('content-encoding')if (encoding && encoding.toLowerCase() !== 'identity')diff --git a/mcp-host/src/visualInput/policy.ts b/mcp-host/src/visualInput/policy.tsindex 6bebf1983..eaa0a4d4e 100644--- a/mcp-host/src/visualInput/policy.ts+++ b/mcp-host/src/visualInput/policy.ts@@ -20,6 +20,7 @@ export type VisualInputErrorCode =| 'unsupported_format'| 'invalid_image'| 'version_conflict'+ | 'identity_mismatch'| 'invalid_response'| 'incomplete_response'| 'cancelled'diff --git a/mcp-host/src/workflow/workflowService.ts b/mcp-host/src/workflow/workflowService.tsindex edd7687a3..af49e8e09 100644--- a/mcp-host/src/workflow/workflowService.ts+++ b/mcp-host/src/workflow/workflowService.ts@@ -1104,7 +1104,10 @@ export class WorkflowService {if (requestedGfsToolNames.size > 0 && gfsScopes.size > 0 && hasGfsRuntimeAccess(gfsEnv)) {const gfsClient = createGfscClient(gfsEnv, { maxRetryWaitMs: timeoutMs })const scopedGfsTools = [- ...(gfsScopes.has('gfs.read') ? buildGfsReadTools(gfsClient) : []),+ // A workflow step has no incoming message, so no file reference pins a version.+ ...(gfsScopes.has('gfs.read')+ ? buildGfsReadTools(gfsClient, { referencedFiles: new Map() })+ : []),...(gfsScopes.has('gfs.write') ? buildGfsWriteTools(gfsClient) : []),].filter(tool => requestedGfsToolNames.has(tool.name))internalTools.push(...scopedGfsTools)