From b85491f3d34c4e20d903253517af9fbba4563b63 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 00:00:05 +0000 Subject: [PATCH 1/5] fix(core): resourceTools reads only llmReadable collections, without secret fields (FIX-2436) readResource resolved a path against every registered collection and returned the full stored state, so a worker given resourceTools() beside a collection it may not show the model (a user's MCP keys) could read it. The read now reaches only a collection that opted in with llmReadable, the gate the content and search tools already apply, and drops the fields the collection names in secret. Any other path answers as one no collection matches. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NczDiGRHaqqMGz8cJxCeoQ --- .changeset/resource-tools-read-gate.md | 5 ++ packages/core/README.md | 2 +- packages/core/src/tools/resource-tools.ts | 17 +++-- .../core/src/types/resource-collection.ts | 5 +- .../test/resource-tools-path-matching.test.ts | 26 ++++++-- .../test/resource-tools-key-read.test.ts | 64 +++++++++++++++++++ 6 files changed, 106 insertions(+), 13 deletions(-) create mode 100644 .changeset/resource-tools-read-gate.md create mode 100644 packages/workforce/test/resource-tools-key-read.test.ts diff --git a/.changeset/resource-tools-read-gate.md b/.changeset/resource-tools-read-gate.md new file mode 100644 index 0000000000..0cb990df60 --- /dev/null +++ b/.changeset/resource-tools-read-gate.md @@ -0,0 +1,5 @@ +--- +"@flow-state-dev/core": patch +--- + +`resourceTools()`'s `readResource` now reads only from a collection that opted in with `llmReadable`, and leaves out the fields the collection names in `secret`. A path into a collection that didn't opt in answers as a path no collection matches. Mark a collection `llmReadable: true` if a model should read its state through this tool (FIX-2436). diff --git a/packages/core/README.md b/packages/core/README.md index 7ddadc267b..8532b48dc3 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -827,7 +827,7 @@ The types are `RequestHost`, `ParentTaskOutcome`, `SettleParentTaskInput`, `Sett **LLM navigation tools.** `resourceSearchTools()` returns the Glob/Grep/Search trio over resources — `globResources` (path glob), `grepResourceContent` (regex/substring over content), and `searchResources` (lexical, term-frequency ranked). All three span static resources and collection instances and return each match's scope-qualified uri — the handle `readResourceContentTool` accepts. All three gate on `llmReadable` (including collection instances whose collection opts in); a collection that did not opt in is skipped before it is listed. Lexical only, not semantic. See [Searching resources](https://flow-state.dev/docs/resources/searching). -**Resource CRUD tools.** `resourceTools()` returns `createResource` / `readResource` / `updateResource` / `deleteResource`, each acting on a path the caller already names. A path reaches the collection whose pattern matches it, by the same rule the collection itself uses: `*` is one segment, `**` is any depth, and `[param]` is one segment bound to that parameter, so `react/observations` reaches `[topic]/observations`. The same path resolves the same instance through `resolveResourceByPath`, and through `resolveResourceByUri` with its scope in front. It no longer returns `listResources`: that tool enumerated every collection's stored state without applying the `llmReadable` gate. To let an agent find out what it can work with, register `resourcesManifestSource()` and give it the discovery tool below. +**Resource CRUD tools.** `resourceTools()` returns `createResource` / `readResource` / `updateResource` / `deleteResource`, each acting on a path the caller already names. `readResource` reads only a collection that opted in with `llmReadable`, and never returns a field the collection names in `secret`; any other path answers as one no collection matches. A path reaches the collection whose pattern matches it, by the same rule the collection itself uses: `*` is one segment, `**` is any depth, and `[param]` is one segment bound to that parameter, so `react/observations` reaches `[topic]/observations`. The same path resolves the same instance through `resolveResourceByPath`, and through `resolveResourceByUri` with its scope in front. It no longer returns `listResources`: that tool enumerated every collection's stored state without applying the `llmReadable` gate. To let an agent find out what it can work with, register `resourcesManifestSource()` and give it the discovery tool below. **Agent discovery.** `discoveryTools(createManifestRegistry([...sources]))` returns `discover({ domain?, detail? })` — one on-demand tool that answers what is in scope for this agent right now. A source projects one domain's existing reader into manifest entries (`{ id, kind, purpose, contract? }`); nothing is stored and nothing is copied. The registry is the fence: the tool can only answer for domains it was built with, so a model-supplied `domain` has no wider list to reach past. `resourcesManifestSource()` ships here; workers (the `workers` domain) and skills are registered by their own packages. diff --git a/packages/core/src/tools/resource-tools.ts b/packages/core/src/tools/resource-tools.ts index 9a9640c90e..4d894dc503 100644 --- a/packages/core/src/tools/resource-tools.ts +++ b/packages/core/src/tools/resource-tools.ts @@ -4,6 +4,8 @@ import type { AnyResourceRef, ResourceRef } from "../types/resource"; import type { ResourceCollectionRef } from "../types/resource-collection"; import type { ResourceVisibility, ResourceVisibilityRule } from "../types/resource-visibility"; import { handler } from "../blocks/handler"; +import { omitSecretFields } from "../helpers/client-projection"; +import type { JsonObject } from "../schema/common"; import { extractBareTopic, isParameterizedPattern, @@ -116,7 +118,8 @@ function collectStaticResources(ctx: BlockContext): ResourceRef[] { * * Provides 4 tools, each acting on a path the caller already names: * - `createResource({ path, state? })` — Create a new resource instance - * - `readResource({ path })` — Read a resource instance + * - `readResource({ path })` — Read a resource instance, in a collection that + * opted in with `llmReadable`, without the fields its `secret` names * - `updateResource({ path, state? })` — Update a resource instance * - `deleteResource({ path })` — Delete a resource instance * @@ -159,7 +162,7 @@ export function resourceTools() { execute: async (input, ctx) => { const { nsRef, key } = resolvePathToCollection(input.path, ctx); const handle = await nsRef.get(key); - return { path: input.path, state: handle.state as Record }; + return { path: input.path, state: omitSecretFields(nsRef.config, handle.state as JsonObject) }; }, }); @@ -353,9 +356,13 @@ function resolvePathToCollection( ctx: BlockContext, intent: "read" | "write" = "read" ): { nsRef: ResourceCollectionRef; key: string | Record } { - // A collection the rule leaves read-only isn't a target for a write: the - // write answers as for a path no collection matches. - const collections = collectCollections(ctx).filter((ns) => intent === "read" || ns.access === "visible"); + // A read reaches only a collection that opted in with `llmReadable`, the same + // gate the content and search tools apply; a collection the rule leaves + // read-only isn't a target for a write. Either way the call answers as for a + // path no collection matches. + const collections = collectCollections(ctx).filter((ns) => + intent === "read" ? ns.ref.config?.llmReadable === true : ns.access === "visible" + ); for (const ns of collections) { const key = matchCollectionKey(ns, path); diff --git a/packages/core/src/types/resource-collection.ts b/packages/core/src/types/resource-collection.ts index eee92417c8..5c5fd7e5bd 100644 --- a/packages/core/src/types/resource-collection.ts +++ b/packages/core/src/types/resource-collection.ts @@ -132,8 +132,9 @@ export type ResourceCollectionConfig = { /** * Expose this collection's instance content to the LLM via the generic content - * tools (`readResourceContentTool`) and content search (`grepResourceContent` / - * `searchResources`). Collection-wide — applies to every instance, the same way + * tools (`readResourceContentTool`), content search (`grepResourceContent` / + * `searchResources`), and instance state via `resourceTools()`'s + * `readResource`, which also leaves out `secret` fields. Collection-wide — applies to every instance, the same way * `client` is declared once at the collection level. Default `false`: a * collection that doesn't opt in stays invisible to those tools. */ diff --git a/packages/engine/test/resource-tools-path-matching.test.ts b/packages/engine/test/resource-tools-path-matching.test.ts index 68c547bc77..cf2e7bbd2e 100644 --- a/packages/engine/test/resource-tools-path-matching.test.ts +++ b/packages/engine/test/resource-tools-path-matching.test.ts @@ -12,6 +12,10 @@ * row sees another row's writes. The existing unit tests stub the collection * refs; this file does not, so the real `get`/`create`/`getOptional` * validation is what answers. + * + * `readResource` answers only from a collection that opted in with + * `llmReadable`, and without the fields its `secret` names: a collection that + * didn't opt in answers as for a path no collection matches. */ import { DEFAULT_ORG_ID, @@ -31,25 +35,31 @@ import { z } from "zod"; import { createExecutionContext, createInMemoryStores } from "../src"; const s = z.object({ v: z.string().default("") }); +const keyed = z.object({ v: z.string().default(""), key: z.string().default("") }); const OWNER = ownerSegment("user_1"); const OTHER = ownerSegment("user_2"); async function makeCtx() { const resources = { profile: defineResource({ scope: "session", stateSchema: s }), - files: defineResourceCollection({ scope: "session", pattern: "files/*", stateSchema: s }), - docs: defineResourceCollection({ scope: "session", pattern: "docs/**", stateSchema: s }), + files: defineResourceCollection({ scope: "session", pattern: "files/*", stateSchema: s, llmReadable: true }), + docs: defineResourceCollection({ scope: "session", pattern: "docs/**", stateSchema: s, llmReadable: true }), // Registered shallow-first on purpose: a shallow collection must not claim // a nested path it can't hold and so hide the deep one behind it. - nestShallow: defineResourceCollection({ scope: "session", pattern: "nest/*", stateSchema: s }), - nestDeep: defineResourceCollection({ scope: "session", pattern: "nest/**", stateSchema: s }), - obs: defineResourceCollection({ scope: "session", pattern: "[topic]/observations", stateSchema: s }), + nestShallow: defineResourceCollection({ scope: "session", pattern: "nest/*", stateSchema: s, llmReadable: true }), + nestDeep: defineResourceCollection({ scope: "session", pattern: "nest/**", stateSchema: s, llmReadable: true }), + obs: defineResourceCollection({ scope: "session", pattern: "[topic]/observations", stateSchema: s, llmReadable: true }), notes: defineResourceCollection({ scope: "org", pattern: "notes/[owner]/[id]", ownerPrivate: { param: "owner" }, stateSchema: s, + llmReadable: true, }), + // Not opted in: blocks reach it, the model doesn't. + vault: defineResourceCollection({ scope: "session", pattern: "vault/*", stateSchema: s }), + // Opted in, with one field that never leaves the server. + keys: defineResourceCollection({ scope: "session", pattern: "keys/*", stateSchema: keyed, llmReadable: true, secret: ["key"] }), positions: defineProjectedResourceCollection({ pattern: "positions/*", scope: "session", @@ -78,6 +88,8 @@ async function makeCtx() { await ctx.resources.nestDeep.create("x/y", { v: "n" }); await ctx.resources.obs.create({ topic: "react" }, { v: "o" }); await ctx.resources.notes.create({ owner: OWNER, id: "mine" }, { v: "m" }); + await ctx.resources.vault.create("linear", { v: "sk-vault" }); + await ctx.resources.keys.create("linear", { v: "set", key: "sk-keys" }); return ctx; } @@ -135,6 +147,10 @@ const ROWS: readonly Row[] = [ [`read notes/${OWNER}/mine`, exec("readResource", { path: `notes/${OWNER}/mine` }), `ok {"path":"notes/${OWNER}/mine","state":{"v":"m"}}`], [`create notes/${OTHER}/theirs`, exec("createResource", { path: `notes/${OTHER}/theirs` }), REFUSED], [`read notes/${OTHER}/mine`, exec("readResource", { path: `notes/${OTHER}/mine` }), REFUSED], + // A collection that didn't opt in with `llmReadable` answers as one nothing registers. + ["read vault/linear", exec("readResource", { path: "vault/linear" }), NO_COLLECTION("vault/linear")], + // An opted-in collection is read without its `secret` fields. + ["read keys/linear", exec("readResource", { path: "keys/linear" }), `ok {"path":"keys/linear","state":{"v":"set"}}`], // ── resolveResourceByPath ───────────────────────────────────────────────── ["byPath profile", byPath("profile"), "ref session/profile"], diff --git a/packages/workforce/test/resource-tools-key-read.test.ts b/packages/workforce/test/resource-tools-key-read.test.ts new file mode 100644 index 0000000000..5e22879782 --- /dev/null +++ b/packages/workforce/test/resource-tools-key-read.test.ts @@ -0,0 +1,64 @@ +/** + * A worker holding a user's MCP keys and core's generic `resourceTools()` on + * the same model can't read a key through `readResource`. + * + * A worker that reaches its project's MCP servers holds the keys collection + * (`mcp-credentials/*`, at user scope) on its model block, so the key is there + * to read. The collection isn't `llmReadable` and declares `value` secret, so + * the model must not be handed it by any generic tool. The worker here picks + * `readResource` from its catalog and holds `mcpCredentialsCapability`, the + * keys collection a project-MCP worker holds; its model asks for the path a + * key is stored at, and the tool's answer is what the test reads. + */ +import { describe, expect, it } from "vitest"; +import { resourceTools } from "@flow-state-dev/core"; +import type { FlowInstance } from "@flow-state-dev/core/types"; +import { executeBlock } from "@flow-state-dev/engine"; +import { createTestContext, mockGenerator } from "@flow-state-dev/testing"; +import { AGENT_FLOW, defineAgentWorkerFlow } from "../src/agent-worker-flow"; +import { mintWorkers } from "../src/hire"; +import { MCP_CREDENTIALS_RESOURCE, mcpCredentialsCapability } from "../src/projects/mcp-credentials"; + +const KEY = "lin_api_users_own_key"; + +async function askForTheKey() { + const { readResource } = resourceTools(); + const flow = defineAgentWorkerFlow({ uses: [mcpCredentialsCapability], catalog: { readResource } }); + const [worker] = mintWorkers([{ id: "desk.lead", declared: { tools: ["readResource"] }, body: "" }], { + workerFlows: { [AGENT_FLOW]: flow } + }) as FlowInstance[]; + const block = worker!.actions.respond!.block; + const model = mockGenerator({ + name: "agent-answer", + script: [ + { toolCalls: [{ toolCallId: "call-1", toolName: "readResource", args: { path: "mcp-credentials/linear" } }] }, + { text: "done" } + ] as never + }); + const runtime = await createTestContext({ + flow: { ...worker!, cardinality: "singleton" }, + orgId: "test-org", + org: { state: {} }, + sessionId: "test-session", + sequencerName: block.name, + declaredResources: block.declaredResources, + generators: { "agent-answer": model } + }); + // The user's key, stored the way a host's settings route stores it. + const keys = (runtime.ctx.resources as unknown as Record }>)[ + MCP_CREDENTIALS_RESOURCE + ]!; + await keys.create("linear", { value: KEY, setAt: "2026-10-31T00:00:00.000Z" }); + + const result = await executeBlock({ block, input: { message: "what is my Linear key?" }, ctx: runtime.ctx }); + return { result, items: JSON.stringify(runtime.getItems()) }; +} + +describe("resourceTools beside a worker's MCP keys", () => { + it("refuses the read, and the key reaches nothing the model sees", async () => { + const { items } = await askForTheKey(); + // The tool ran and answered as for a path no collection matches. + expect(items).toContain("No resource collection found matching path: mcp-credentials/linear"); + expect(items).not.toContain(KEY); + }); +}); From 40814a1200622361d26de58fbca818a360511281 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 00:02:03 +0000 Subject: [PATCH 2/5] test(workforce): rename the key-read helper off a retired term (FIX-2436) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NczDiGRHaqqMGz8cJxCeoQ --- packages/workforce/test/resource-tools-key-read.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/workforce/test/resource-tools-key-read.test.ts b/packages/workforce/test/resource-tools-key-read.test.ts index 5e22879782..2ae13c9ad4 100644 --- a/packages/workforce/test/resource-tools-key-read.test.ts +++ b/packages/workforce/test/resource-tools-key-read.test.ts @@ -21,7 +21,7 @@ import { MCP_CREDENTIALS_RESOURCE, mcpCredentialsCapability } from "../src/proje const KEY = "lin_api_users_own_key"; -async function askForTheKey() { +async function requestTheKey() { const { readResource } = resourceTools(); const flow = defineAgentWorkerFlow({ uses: [mcpCredentialsCapability], catalog: { readResource } }); const [worker] = mintWorkers([{ id: "desk.lead", declared: { tools: ["readResource"] }, body: "" }], { @@ -56,7 +56,7 @@ async function askForTheKey() { describe("resourceTools beside a worker's MCP keys", () => { it("refuses the read, and the key reaches nothing the model sees", async () => { - const { items } = await askForTheKey(); + const { items } = await requestTheKey(); // The tool ran and answered as for a path no collection matches. expect(items).toContain("No resource collection found matching path: mcp-credentials/linear"); expect(items).not.toContain(KEY); From 58689db007007292b73e407cf2f50fc020184a6c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 00:04:11 +0000 Subject: [PATCH 3/5] chore(changeset): mark the readResource gate minor, since it can break a consumer (FIX-2436) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NczDiGRHaqqMGz8cJxCeoQ --- .changeset/resource-tools-read-gate.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/resource-tools-read-gate.md b/.changeset/resource-tools-read-gate.md index 0cb990df60..d24e078a7d 100644 --- a/.changeset/resource-tools-read-gate.md +++ b/.changeset/resource-tools-read-gate.md @@ -1,5 +1,5 @@ --- -"@flow-state-dev/core": patch +"@flow-state-dev/core": minor --- `resourceTools()`'s `readResource` now reads only from a collection that opted in with `llmReadable`, and leaves out the fields the collection names in `secret`. A path into a collection that didn't opt in answers as a path no collection matches. Mark a collection `llmReadable: true` if a model should read its state through this tool (FIX-2436). From 358ff5022f6232d404d261b196d7dd8be45335cc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 00:05:31 +0000 Subject: [PATCH 4/5] refactor(core): one collection read gate for list, search and readResource (FIX-2436) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NczDiGRHaqqMGz8cJxCeoQ --- packages/core/src/tools/resource-tools.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/packages/core/src/tools/resource-tools.ts b/packages/core/src/tools/resource-tools.ts index 4d894dc503..48dbac5763 100644 --- a/packages/core/src/tools/resource-tools.ts +++ b/packages/core/src/tools/resource-tools.ts @@ -251,6 +251,15 @@ export function isLlmReadable(ref: ResourceRef): boolean { return ref.config?.llmReadable === true; } +/** + * The collection-level read gate: whether a collection opted in with + * `llmReadable`. Every tool that lists, searches or reads a collection for the + * model asks this one function, so the gate can't drift between them. + */ +function isCollectionLlmReadable(ns: CollectionEntry): boolean { + return ns.ref.config?.llmReadable === true; +} + /** Content write gate. Independent of `llmReadable`, matching the single-resource contract. */ export function isLlmWritable(ref: ResourceRef): boolean { return ref.config?.llmWritable === true; @@ -285,7 +294,7 @@ export function isLlmWritableNow(ref: ResourceRef, ctx: BlockContext): bool export async function collectReadableResources(ctx: BlockContext): Promise[]> { const out: ResourceRef[] = collectStaticResources(ctx).filter(isLlmReadable); for (const ns of collectCollections(ctx)) { - if (ns.ref.config?.llmReadable !== true) continue; + if (!isCollectionLlmReadable(ns)) continue; for (const instance of await ns.ref.list()) out.push(instance); } return out; @@ -303,7 +312,7 @@ export async function collectReadableResources(ctx: BlockContext): Promise ns.ref.config?.llmReadable === true); + return collectProjectedCollections(ctx).filter(isCollectionLlmReadable); } /** @@ -361,7 +370,7 @@ function resolvePathToCollection( // read-only isn't a target for a write. Either way the call answers as for a // path no collection matches. const collections = collectCollections(ctx).filter((ns) => - intent === "read" ? ns.ref.config?.llmReadable === true : ns.access === "visible" + intent === "read" ? isCollectionLlmReadable(ns) : ns.access === "visible" ); for (const ns of collections) { From f23369de3691b35d2c430b06e1582c51a4fe40ba Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 1 Nov 2026 00:10:54 +0000 Subject: [PATCH 5/5] refactor(core): share isLlmReadable with collection reads The collection helper repeated the same config.llmReadable check. The exported gate now accepts a collection ref, so list, search, and readResource call it. Co-authored-by: Jake Hoffner --- packages/core/src/tools/resource-tools.ts | 22 ++++++---------------- 1 file changed, 6 insertions(+), 16 deletions(-) diff --git a/packages/core/src/tools/resource-tools.ts b/packages/core/src/tools/resource-tools.ts index 48dbac5763..a8bd97e51f 100644 --- a/packages/core/src/tools/resource-tools.ts +++ b/packages/core/src/tools/resource-tools.ts @@ -243,23 +243,13 @@ export async function resolveResourceByPath( } /** - * Content read gate. A collection instance carries its owning collection's - * config (the server stamps `config: nsConfig` onto every instance ref), so the - * collection-level `llmReadable` flag reaches each instance through `ref.config`. + * Content read gate. `config.llmReadable === true`, on a static resource, a + * collection, or an instance (an instance carries its collection's config). */ -export function isLlmReadable(ref: ResourceRef): boolean { +export function isLlmReadable(ref: ResourceRef | ResourceCollectionRef): boolean { return ref.config?.llmReadable === true; } -/** - * The collection-level read gate: whether a collection opted in with - * `llmReadable`. Every tool that lists, searches or reads a collection for the - * model asks this one function, so the gate can't drift between them. - */ -function isCollectionLlmReadable(ns: CollectionEntry): boolean { - return ns.ref.config?.llmReadable === true; -} - /** Content write gate. Independent of `llmReadable`, matching the single-resource contract. */ export function isLlmWritable(ref: ResourceRef): boolean { return ref.config?.llmWritable === true; @@ -294,7 +284,7 @@ export function isLlmWritableNow(ref: ResourceRef, ctx: BlockContext): bool export async function collectReadableResources(ctx: BlockContext): Promise[]> { const out: ResourceRef[] = collectStaticResources(ctx).filter(isLlmReadable); for (const ns of collectCollections(ctx)) { - if (!isCollectionLlmReadable(ns)) continue; + if (!isLlmReadable(ns.ref)) continue; for (const instance of await ns.ref.list()) out.push(instance); } return out; @@ -312,7 +302,7 @@ export async function collectReadableResources(ctx: BlockContext): Promise isLlmReadable(ns.ref)); } /** @@ -370,7 +360,7 @@ function resolvePathToCollection( // read-only isn't a target for a write. Either way the call answers as for a // path no collection matches. const collections = collectCollections(ctx).filter((ns) => - intent === "read" ? isCollectionLlmReadable(ns) : ns.access === "visible" + intent === "read" ? isLlmReadable(ns.ref) : ns.access === "visible" ); for (const ns of collections) {