@tpsdev-ai/flair 0.56.0 → 0.58.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 +19 -20
- package/SECURITY.md +4 -1
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1800 -293
- package/dist/commands/agent.js +22 -15
- package/dist/commands/bridge.js +40 -3
- package/dist/commands/doctor.js +214 -4
- package/dist/commands/federation.js +265 -38
- package/dist/commands/hook.js +10 -2
- package/dist/commands/init.js +179 -48
- package/dist/commands/memory.js +24 -2
- package/dist/commands/quality.js +26 -18
- package/dist/commands/service.js +137 -22
- package/dist/commands/status.js +114 -3
- package/dist/commands/upgrade.js +204 -84
- package/dist/doctor-client.js +50 -4
- package/dist/federation/scheduler.js +253 -4
- package/dist/install/clients.js +89 -23
- package/dist/install/global-bin-path.js +26 -6
- package/dist/lib/atomic-write.js +256 -0
- package/dist/lib/auth-resolve.js +46 -0
- package/dist/lib/daemon-liveness.js +61 -0
- package/dist/lib/doctor-run.js +5 -0
- package/dist/lib/embed-gpu-doctor.js +49 -26
- package/dist/lib/federation-memory-attributes.js +15 -0
- package/dist/lib/init-admin-pass.js +4 -2
- package/dist/lib/init-listener-environ.js +38 -0
- package/dist/lib/init-occupied-listener.js +165 -0
- package/dist/lib/instance-identity-row.js +580 -0
- package/dist/lib/launchd-domain-preflight.js +448 -0
- package/dist/lib/launchd-management.js +176 -6
- package/dist/lib/launchd-repair.js +95 -0
- package/dist/lib/memory-attributes.js +77 -0
- package/dist/lib/node-alias-path.js +95 -0
- package/dist/lib/npm-registry.js +119 -6
- package/dist/lib/owned-pins.js +20 -6
- package/dist/lib/redact-token-id.js +197 -0
- package/dist/lib/service-repoint-apply.js +267 -0
- package/dist/lib/service-repoint.js +575 -0
- package/dist/lib/toml-string-array.js +104 -0
- package/dist/lib/tree-divergence.js +716 -0
- package/dist/lib/upgrade-plain-tree.js +18 -8
- package/dist/lib/upgrade-prior-liveness.js +69 -0
- package/dist/lib/upgrade-rollback.js +116 -0
- package/dist/rem/runner.js +11 -0
- package/dist/resources/Agent.js +27 -14
- package/dist/resources/AgentSeed.js +39 -2
- package/dist/resources/Asset.js +3 -11
- package/dist/resources/Credential.js +4 -10
- package/dist/resources/Federation.js +299 -127
- package/dist/resources/Integration.js +8 -32
- package/dist/resources/Memory.js +623 -86
- package/dist/resources/MemoryArchive.js +9 -0
- package/dist/resources/MemoryBootstrap.js +23 -12
- package/dist/resources/MemoryCandidate.js +3 -11
- package/dist/resources/MemoryDedupStats.js +1 -1
- package/dist/resources/MemoryFeed.js +214 -5
- package/dist/resources/MemoryGrant.js +19 -40
- package/dist/resources/MemoryHostSource.js +90 -0
- package/dist/resources/MemoryMaintenance.js +121 -32
- package/dist/resources/MemoryReflect.js +4 -1
- package/dist/resources/MemoryReindex.js +7 -4
- package/dist/resources/MemoryUsage.js +55 -18
- package/dist/resources/Presence.js +18 -10
- package/dist/resources/RecordUsage.js +30 -40
- package/dist/resources/Relationship.js +170 -89
- package/dist/resources/SemanticSearch.js +44 -19
- package/dist/resources/Soul.js +31 -19
- package/dist/resources/XAA.js +7 -3
- package/dist/resources/agent-auth.js +16 -10
- package/dist/resources/auth-middleware.js +164 -50
- package/dist/resources/auto-promote-lib.js +4 -4
- package/dist/resources/bm25-index-service.js +246 -32
- package/dist/resources/bm25-status.js +132 -0
- package/dist/resources/bm25.js +13 -14
- package/dist/resources/ed25519-auth.js +11 -54
- package/dist/resources/embed-gpu.js +262 -47
- package/dist/resources/embeddings-boot.js +52 -17
- package/dist/resources/federation-classify.js +12 -0
- package/dist/resources/federation-cleanup.js +289 -51
- package/dist/resources/federation-crypto.js +65 -19
- package/dist/resources/health.js +105 -22
- package/dist/resources/host-pointer/registry.js +35 -0
- package/dist/resources/host-pointer-adapter.js +15 -0
- package/dist/resources/host-source-visibility.js +167 -0
- package/dist/resources/host-source.js +151 -0
- package/dist/resources/in-process-api.js +2 -1
- package/dist/resources/instance-create-lock.js +363 -0
- package/dist/resources/instance-identity-rows.js +43 -0
- package/dist/resources/instance-identity.js +97 -12
- package/dist/resources/mcp-handler.js +155 -51
- package/dist/resources/mcp-tool-arguments.js +83 -0
- package/dist/resources/mcp-tools.js +28 -25
- package/dist/resources/memory-consolidate-lib.js +3 -1
- package/dist/resources/memory-declared-attributes.js +103 -0
- package/dist/resources/memory-feed-lib.js +5 -1
- package/dist/resources/memory-host-source.js +163 -0
- package/dist/resources/memory-visibility.js +10 -7
- package/dist/resources/migrations/synthetic-test-migration.js +4 -1
- package/dist/resources/migrations/visibility-backfill.js +4 -1
- package/dist/resources/originator-instance.js +235 -0
- package/dist/resources/promotion-stamp.js +2 -0
- package/dist/resources/provenance.js +111 -11
- package/dist/resources/rate-limit.js +6 -4
- package/dist/resources/record-owner-guard.js +19 -0
- package/dist/resources/record-type-kit.js +44 -23
- package/dist/resources/record-types.js +6 -6
- package/dist/resources/relay-ops.js +28 -3
- package/dist/resources/replay-store.js +289 -0
- package/dist/resources/request-transaction.js +78 -0
- package/dist/resources/search-readiness.js +26 -22
- package/dist/resources/semantic-retrieval-core.js +103 -4
- package/dist/resources/table-helpers.js +33 -0
- package/dist/resources/table-patch-policy.js +109 -0
- package/dist/resources/table-patches.js +17 -0
- package/dist/resources/table-post-policy.js +138 -0
- package/dist/resources/table-posts.js +22 -0
- package/dist/resources/table-subscription-policy.js +135 -0
- package/dist/resources/table-subscriptions.js +19 -0
- package/dist/resources/tool-descriptors/index.js +15 -15
- package/dist/resources/trust-block.js +10 -3
- package/dist/resources/usage-recording.js +169 -41
- package/dist/src/lib/instance-identity-row.js +580 -0
- package/dist/src/lib/memory-attributes.js +77 -0
- package/dist/src/lib/redact-token-id.js +197 -0
- package/docs/api-reference.md +80 -16
- package/docs/auth.md +5 -5
- package/docs/claude-code.md +137 -6
- package/docs/deploying-on-fabric.md +6 -3
- package/docs/deployment.md +1 -1
- package/docs/embedding-in-a-harper-app.md +3 -3
- package/docs/federation.md +17 -10
- package/docs/hosted-on-fabric.md +4 -3
- package/docs/integrations.md +28 -19
- package/docs/mcp-clients.md +26 -32
- package/docs/n8n.md +8 -8
- package/docs/notes/mcp-oauth-model2.md +27 -18
- package/docs/openclaw.md +29 -28
- package/docs/quickstart.md +5 -0
- package/docs/releasing.md +134 -2
- package/docs/spoke-bringup.md +14 -11
- package/docs/standalone-local.md +2 -2
- package/docs/supply-chain-policy.md +28 -10
- package/docs/system-requirements.md +1 -1
- package/docs/troubleshooting.md +11 -0
- package/docs/upgrade.md +189 -63
- package/package.json +9 -5
- package/schemas/agent.graphql +9 -6
- package/schemas/federation.graphql +2 -11
- package/schemas/memory.graphql +106 -17
- package/schemas/replay.graphql +18 -0
- package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
- package/dist/resources/federation-nonce-store.js +0 -195
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* mcp-handler.ts — the Model-2 custom MCP protocol handler.
|
|
3
3
|
*
|
|
4
|
-
* A minimal in-process MCP (JSON-RPC 2.0) handler serving the
|
|
5
|
-
* tools over Streamable HTTP. It is wrapped by `@harperfast/oauth`'s
|
|
4
|
+
* A minimal in-process MCP (JSON-RPC 2.0) handler serving the curated flair
|
|
5
|
+
* tools (resources/mcp-tools.ts's TOOLS) over Streamable HTTP. It is wrapped by `@harperfast/oauth`'s
|
|
6
6
|
* `withMCPAuth` (see mcp-oauth.ts), which fails closed on any missing/invalid
|
|
7
7
|
* Bearer token BEFORE this handler runs and, on success, sets
|
|
8
8
|
* `request.mcp = { sub, client_id, aud, scope }` (verified RS256 JWT claims).
|
|
@@ -26,7 +26,10 @@
|
|
|
26
26
|
import { databases } from "harper";
|
|
27
27
|
import { randomBytes } from "node:crypto";
|
|
28
28
|
import { TOOLS, listToolDefs } from "./mcp-tools.js";
|
|
29
|
+
import { checkToolArguments, withoutNullArguments } from "./mcp-tool-arguments.js";
|
|
29
30
|
import { agentRecordIsAdmin } from "./agent-admin.js";
|
|
31
|
+
import { isPrincipalDeactivated } from "./agent-auth.js";
|
|
32
|
+
import { stampOriginatorOnCreate } from "./originator-instance.js";
|
|
30
33
|
import { resolveVersion } from "./version.js";
|
|
31
34
|
// The MCP protocol revision we implement (initialize handshake).
|
|
32
35
|
const PROTOCOL_VERSION = "2025-06-18";
|
|
@@ -158,15 +161,35 @@ function jitProvisionEnabled() {
|
|
|
158
161
|
* `undefined` — so existing callers/tests that don't pass one see the exact
|
|
159
162
|
* same `{ agentId, isAdmin }` shape as before this field existed.
|
|
160
163
|
*
|
|
164
|
+
* When a Credential maps the sub, the mapped principal must exist and be
|
|
165
|
+
* active — the rule the Ed25519 path applies (resources/agent-auth.ts,
|
|
166
|
+
* `isPrincipalDeactivated`) — and its record is read on every resolution, so a
|
|
167
|
+
* token minted while the principal was active stops resolving once the
|
|
168
|
+
* principal is deactivated. If that read fails, or the credential lookup itself
|
|
169
|
+
* fails, resolution is refused. An unreadable answer is never taken as
|
|
170
|
+
* "allowed", and never as "no mapping": JIT provisioning runs only for a
|
|
171
|
+
* subject the credential lookup answered for. Resolution writes nothing to an
|
|
172
|
+
* existing credential; the handler updates its `lastUsedAt`, best effort, after
|
|
173
|
+
* a tool has run (handleToolCall).
|
|
174
|
+
*
|
|
161
175
|
* Returns:
|
|
162
|
-
* - `{ agentId, isAdmin, clientId? }` when a Credential maps the sub to an
|
|
176
|
+
* - `{ agentId, isAdmin, clientId? }` when a Credential maps the sub to an
|
|
177
|
+
* existing, active Agent.
|
|
163
178
|
* - null when no Credential maps the sub AND JIT-provisioning is disabled or
|
|
164
179
|
* failed → the handler denies the tool call (sub is unresolvable).
|
|
180
|
+
*
|
|
181
|
+
* Throws `PrincipalRefusedError` (the handler returns its JSON-RPC error) when
|
|
182
|
+
* the mapped principal is deactivated or missing, or when the credential or
|
|
183
|
+
* principal could not be read.
|
|
165
184
|
*/
|
|
166
185
|
export async function resolveAgentFromSub(sub, clientId) {
|
|
186
|
+
return (await resolveMapping(sub, clientId))?.agent ?? null;
|
|
187
|
+
}
|
|
188
|
+
async function resolveMapping(sub, clientId) {
|
|
167
189
|
if (!sub)
|
|
168
190
|
return null;
|
|
169
191
|
// 1. Existing IdP credential → its principalId is the Agent id.
|
|
192
|
+
let mapped = null;
|
|
170
193
|
try {
|
|
171
194
|
for await (const cred of databases.flair.Credential.search({
|
|
172
195
|
conditions: [
|
|
@@ -175,29 +198,33 @@ export async function resolveAgentFromSub(sub, clientId) {
|
|
|
175
198
|
],
|
|
176
199
|
})) {
|
|
177
200
|
if (cred?.principalId && cred.status !== "revoked") {
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
await databases.flair.Credential.put({ ...cred, lastUsedAt: new Date().toISOString() });
|
|
181
|
-
}
|
|
182
|
-
catch { /* non-fatal */ }
|
|
183
|
-
const resolved = { agentId: String(cred.principalId), isAdmin: await isAgentAdmin(cred.principalId) };
|
|
184
|
-
if (clientId)
|
|
185
|
-
resolved.clientId = clientId;
|
|
186
|
-
return resolved;
|
|
201
|
+
mapped = cred;
|
|
202
|
+
break;
|
|
187
203
|
}
|
|
188
204
|
}
|
|
189
205
|
}
|
|
190
|
-
catch {
|
|
206
|
+
catch {
|
|
207
|
+
throw new PrincipalRefusedError(-32000, "unavailable: the credential for this token's subject could not be read, so the call was refused. " +
|
|
208
|
+
"Retry; if this persists, an operator should check the flair server log.");
|
|
209
|
+
}
|
|
210
|
+
if (mapped) {
|
|
211
|
+
const principalId = String(mapped.principalId);
|
|
212
|
+
const principal = await requireActivePrincipal(principalId);
|
|
213
|
+
const resolved = { agentId: principalId, isAdmin: agentRecordIsAdmin(principal) };
|
|
214
|
+
if (clientId)
|
|
215
|
+
resolved.clientId = clientId;
|
|
216
|
+
return { agent: resolved, credential: mapped };
|
|
217
|
+
}
|
|
191
218
|
// 2. No mapping. JIT-provision only behind the explicit trust anchor.
|
|
192
219
|
if (!jitProvisionEnabled())
|
|
193
220
|
return null;
|
|
194
221
|
try {
|
|
195
|
-
const principalId = await jitProvisionPrincipal(sub);
|
|
222
|
+
const { principalId, credential } = await jitProvisionPrincipal(sub);
|
|
196
223
|
// A JIT-provisioned principal is a fresh, non-admin agent by construction.
|
|
197
224
|
const resolved = { agentId: principalId, isAdmin: false };
|
|
198
225
|
if (clientId)
|
|
199
226
|
resolved.clientId = clientId;
|
|
200
|
-
return resolved;
|
|
227
|
+
return { agent: resolved, credential };
|
|
201
228
|
}
|
|
202
229
|
catch {
|
|
203
230
|
return null;
|
|
@@ -208,11 +235,15 @@ export async function resolveAgentFromSub(sub, clientId) {
|
|
|
208
235
|
* token subject. Mirrors XAA.resolveOrCreatePrincipal's provisioning shape (the
|
|
209
236
|
* `Credential.kind:"idp"` + `idpSubject` surface) but keyed on the MCP token sub.
|
|
210
237
|
* The created agent is non-admin, `kind:"agent"`, unverified trust tier.
|
|
238
|
+
* Returns the principal id and the new credential, which is created without
|
|
239
|
+
* `lastUsedAt`.
|
|
211
240
|
*/
|
|
212
241
|
async function jitProvisionPrincipal(sub) {
|
|
213
242
|
const now = new Date().toISOString();
|
|
214
243
|
const principalId = `agt_mcp_${sub.replace(/[^a-zA-Z0-9]/g, "_").slice(0, 24)}_${randomBytes(4).toString("hex")}`;
|
|
215
|
-
|
|
244
|
+
// flair#1965 r2: this is a raw Agent create (it bypasses the Agent resource's
|
|
245
|
+
// post()), so stamp the local instance id here — every create path carries it.
|
|
246
|
+
const principalRow = {
|
|
216
247
|
id: principalId,
|
|
217
248
|
name: principalId,
|
|
218
249
|
displayName: principalId,
|
|
@@ -226,8 +257,10 @@ async function jitProvisionPrincipal(sub) {
|
|
|
226
257
|
admin: false,
|
|
227
258
|
createdAt: now,
|
|
228
259
|
updatedAt: now,
|
|
229
|
-
}
|
|
230
|
-
await
|
|
260
|
+
};
|
|
261
|
+
await stampOriginatorOnCreate(principalRow);
|
|
262
|
+
await databases.flair.Agent.put(principalRow);
|
|
263
|
+
const credential = {
|
|
231
264
|
id: `cred_mcp_${randomBytes(8).toString("hex")}`,
|
|
232
265
|
principalId,
|
|
233
266
|
kind: "idp",
|
|
@@ -236,32 +269,57 @@ async function jitProvisionPrincipal(sub) {
|
|
|
236
269
|
idpProvider: "mcp-oauth",
|
|
237
270
|
idpSubject: sub,
|
|
238
271
|
createdAt: now,
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
return principalId;
|
|
272
|
+
};
|
|
273
|
+
await databases.flair.Credential.put(credential);
|
|
274
|
+
return { principalId, credential };
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* A token subject whose principal may not call tools. `rpcCode` and the message
|
|
278
|
+
* are the JSON-RPC error the handler returns. The message names the principal
|
|
279
|
+
* when there is one, and says what an operator has to do, or that the caller
|
|
280
|
+
* should retry after a failed read.
|
|
281
|
+
*/
|
|
282
|
+
export class PrincipalRefusedError extends Error {
|
|
283
|
+
rpcCode;
|
|
284
|
+
constructor(rpcCode, message) {
|
|
285
|
+
super(message);
|
|
286
|
+
this.name = "PrincipalRefusedError";
|
|
287
|
+
this.rpcCode = rpcCode;
|
|
288
|
+
}
|
|
242
289
|
}
|
|
243
290
|
/**
|
|
244
|
-
*
|
|
245
|
-
*
|
|
246
|
-
*
|
|
291
|
+
* Read the mapped principal for this call and require it to exist and be
|
|
292
|
+
* active (`isPrincipalDeactivated`, the predicate the Ed25519 path uses: a
|
|
293
|
+
* record with no `status` field counts as active).
|
|
294
|
+
* Returns the principal record; throws `PrincipalRefusedError` otherwise,
|
|
295
|
+
* including when the record cannot be read.
|
|
247
296
|
*
|
|
248
|
-
*
|
|
249
|
-
*
|
|
250
|
-
*
|
|
251
|
-
*
|
|
252
|
-
*
|
|
253
|
-
* path produces, and which was never an admin on the HTTP gate — is no longer
|
|
254
|
-
* an admin here either; see resources/agent-admin.ts for the remedy. This
|
|
255
|
-
* surface is gated behind FLAIR_MCP_OAUTH and is default-OFF.
|
|
297
|
+
* Admin status is read from the same record, through the one shared predicate
|
|
298
|
+
* (resources/agent-admin.ts, flair#941): a MCP-OAuth agent is NON-admin unless
|
|
299
|
+
* an operator has set its Agent record's `role` to "admin" — the MCP surface
|
|
300
|
+
* never elevates on its own. This surface is gated behind FLAIR_MCP_OAUTH and is
|
|
301
|
+
* default-OFF.
|
|
256
302
|
*/
|
|
257
|
-
async function
|
|
303
|
+
async function requireActivePrincipal(principalId) {
|
|
304
|
+
let principal;
|
|
258
305
|
try {
|
|
259
|
-
|
|
260
|
-
return agentRecordIsAdmin(agent);
|
|
306
|
+
principal = await databases.flair.Agent.get(principalId);
|
|
261
307
|
}
|
|
262
308
|
catch {
|
|
263
|
-
|
|
309
|
+
throw new PrincipalRefusedError(-32000, `unavailable: the status of principal '${principalId}' could not be read, so the call was refused. ` +
|
|
310
|
+
"Retry; if this persists, an operator should check the flair server log.");
|
|
311
|
+
}
|
|
312
|
+
if (principal == null) {
|
|
313
|
+
throw new PrincipalRefusedError(-32001, `forbidden: this token's subject maps to principal '${principalId}', which does not exist. ` +
|
|
314
|
+
"An operator must map the subject to an existing principal: a full `flair mcp enable` run against " +
|
|
315
|
+
"this instance, with --principal <agent-id> and --idp-subject <subject>, writes that mapping in its " +
|
|
316
|
+
"identity-mapping step.");
|
|
317
|
+
}
|
|
318
|
+
if (isPrincipalDeactivated(principal)) {
|
|
319
|
+
throw new PrincipalRefusedError(-32001, `forbidden: principal '${principalId}' is deactivated, so this token can no longer call tools. ` +
|
|
320
|
+
"An operator must reactivate the principal (set its status to \"active\") to restore access.");
|
|
264
321
|
}
|
|
322
|
+
return principal;
|
|
265
323
|
}
|
|
266
324
|
// ─── MCP protocol dispatch ───────────────────────────────────────────────────
|
|
267
325
|
/**
|
|
@@ -342,28 +400,74 @@ async function handleToolCall(request, id, params) {
|
|
|
342
400
|
// turn a server-verified, stable id into caller-forgeable data landing in
|
|
343
401
|
// stored provenance. Absent/non-string client_id → omitted, not invented.
|
|
344
402
|
const clientId = typeof request?.mcp?.client_id === "string" ? request.mcp.client_id : undefined;
|
|
345
|
-
|
|
346
|
-
|
|
403
|
+
// For a call that resolves through an existing credential mapping, the
|
|
404
|
+
// principal's status is read here, on every such call (resolveMapping): a
|
|
405
|
+
// deactivated or missing principal, or one whose status cannot be read, is
|
|
406
|
+
// refused with the actionable error it carries.
|
|
407
|
+
let mapping;
|
|
408
|
+
try {
|
|
409
|
+
mapping = await resolveMapping(String(sub), clientId);
|
|
410
|
+
}
|
|
411
|
+
catch (err) {
|
|
412
|
+
if (err instanceof PrincipalRefusedError)
|
|
413
|
+
return rpcError(id, err.rpcCode, err.message);
|
|
414
|
+
return rpcError(id, -32000, "unavailable: the token subject could not be resolved to a principal, so the call was refused. " +
|
|
415
|
+
"Retry; if this persists, an operator should check the flair server log.");
|
|
416
|
+
}
|
|
417
|
+
if (!mapping) {
|
|
347
418
|
// Sub verified by the AS but not mapped to a flair Agent (and JIT disabled /
|
|
348
419
|
// failed). Deny — do NOT fall back to anonymous or admin.
|
|
349
420
|
return rpcError(id, -32001, "forbidden: token subject is not a provisioned flair agent");
|
|
350
421
|
}
|
|
422
|
+
const agent = mapping.agent;
|
|
423
|
+
// The tool implementations are written for their declared argument types;
|
|
424
|
+
// a value of another type is refused before the tool runs, and a null
|
|
425
|
+
// optional argument is treated as absent rather than forwarded.
|
|
426
|
+
const argError = checkToolArguments(entry.def.inputSchema, params?.arguments);
|
|
427
|
+
if (argError)
|
|
428
|
+
return rpcError(id, -32602, `invalid arguments for ${toolName}: ${argError}`);
|
|
429
|
+
const toolArgs = withoutNullArguments(args);
|
|
430
|
+
let result;
|
|
351
431
|
try {
|
|
352
|
-
|
|
353
|
-
// MCP tools/call result: content blocks. Surface the handler's JSON payload
|
|
354
|
-
// as a text block (structuredContent carries the raw object for programmatic
|
|
355
|
-
// clients). A handler-level error object (from unwrap of a Response) is
|
|
356
|
-
// reported as an MCP tool error (isError) rather than a JSON-RPC error, so
|
|
357
|
-
// the client sees the structured message.
|
|
358
|
-
const text = typeof result === "string" ? result : JSON.stringify(result);
|
|
359
|
-
const isError = !!(result && typeof result === "object" && "error" in result && "status" in result);
|
|
360
|
-
return rpcResult(id, {
|
|
361
|
-
content: [{ type: "text", text }],
|
|
362
|
-
structuredContent: typeof result === "object" ? result : { value: result },
|
|
363
|
-
isError,
|
|
364
|
-
});
|
|
432
|
+
result = await entry.impl(agent, toolArgs);
|
|
365
433
|
}
|
|
366
434
|
catch (err) {
|
|
367
435
|
return rpcError(id, -32000, `tool execution failed: ${err?.message ?? String(err)}`);
|
|
368
436
|
}
|
|
437
|
+
// The tool has run and returned (a tool-level error result included): only
|
|
438
|
+
// now is the mapping credential, a JIT-provisioned one included, marked used.
|
|
439
|
+
// A refused call, rejected arguments, or a tool that throws leave `lastUsedAt`
|
|
440
|
+
// as it was. Best effort: a failed write is ignored and does not change the
|
|
441
|
+
// answer.
|
|
442
|
+
await touchLastUsed(mapping.credential);
|
|
443
|
+
// MCP tools/call result: content blocks. Surface the handler's JSON payload
|
|
444
|
+
// as a text block (structuredContent carries the raw object for programmatic
|
|
445
|
+
// clients). A handler-level error object (from unwrap of a Response) is
|
|
446
|
+
// reported as an MCP tool error (isError) rather than a JSON-RPC error, so
|
|
447
|
+
// the client sees the structured message.
|
|
448
|
+
const text = typeof result === "string" ? result : JSON.stringify(result);
|
|
449
|
+
const isError = !!(result && typeof result === "object" && "error" in result && "status" in result);
|
|
450
|
+
return rpcResult(id, {
|
|
451
|
+
content: [{ type: "text", text }],
|
|
452
|
+
structuredContent: typeof result === "object" ? result : { value: result },
|
|
453
|
+
isError,
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Mark the mapping credential used, once a tool has run (best-effort). The
|
|
458
|
+
* update writes `lastUsedAt` alone, as a field-level patch from an internal
|
|
459
|
+
* context (no request, no user), and is skipped when a read just before it
|
|
460
|
+
* finds no stored credential row.
|
|
461
|
+
*/
|
|
462
|
+
async function touchLastUsed(credential) {
|
|
463
|
+
const credentialId = credential?.id;
|
|
464
|
+
if (credentialId == null)
|
|
465
|
+
return;
|
|
466
|
+
try {
|
|
467
|
+
const Credential = databases.flair.Credential;
|
|
468
|
+
if ((await Credential.get(credentialId, {})) == null)
|
|
469
|
+
return;
|
|
470
|
+
await Credential.patch(credentialId, { lastUsedAt: new Date().toISOString() }, {});
|
|
471
|
+
}
|
|
472
|
+
catch { /* non-fatal: a failure here does not change the call's answer */ }
|
|
369
473
|
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime check of a native /mcp `tools/call` arguments object against the
|
|
3
|
+
* declared argument types and required properties of the tool's inputSchema,
|
|
4
|
+
* before the tool runs. JSON-RPC arguments are
|
|
5
|
+
* untyped at runtime; the tool implementations are written for the declared
|
|
6
|
+
* types, so a value of another type is refused here instead of reaching them.
|
|
7
|
+
*
|
|
8
|
+
* Checked at the top level of the schema (the native tools declare only
|
|
9
|
+
* top-level primitive, array and object properties):
|
|
10
|
+
* - the arguments are a plain object (or absent, meaning {});
|
|
11
|
+
* - every `required` property is present (not undefined or null);
|
|
12
|
+
* - every present, non-null property matches its declared `type` (string,
|
|
13
|
+
* number, integer, boolean, array, object; a type list allows any of them),
|
|
14
|
+
* and an array's items match `items.type` when it declares one;
|
|
15
|
+
* - when the schema declares an `id` argument, it is a non-empty string (ids
|
|
16
|
+
* address one record).
|
|
17
|
+
* Properties the schema does not declare, and enum values, are left to the
|
|
18
|
+
* tool, as before. withoutNullArguments() then drops null-valued properties so
|
|
19
|
+
* a tool never forwards a null where its schema declares a type.
|
|
20
|
+
*/
|
|
21
|
+
function matches(value, type) {
|
|
22
|
+
switch (type) {
|
|
23
|
+
case "string": return typeof value === "string";
|
|
24
|
+
case "number": return typeof value === "number" && Number.isFinite(value);
|
|
25
|
+
case "integer": return typeof value === "number" && Number.isInteger(value);
|
|
26
|
+
case "boolean": return typeof value === "boolean";
|
|
27
|
+
case "array": return Array.isArray(value);
|
|
28
|
+
case "object": return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
29
|
+
case "null": return value === null;
|
|
30
|
+
default: return true; // an undeclared or unknown type constrains nothing
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function matchesAny(value, declared) {
|
|
34
|
+
if (declared === undefined)
|
|
35
|
+
return true;
|
|
36
|
+
const types = (Array.isArray(declared) ? declared : [declared]);
|
|
37
|
+
return types.some((t) => matches(value, t));
|
|
38
|
+
}
|
|
39
|
+
/** Returns a message naming the first non-conforming argument, or null. */
|
|
40
|
+
export function checkToolArguments(schema, args) {
|
|
41
|
+
const value = args === undefined ? {} : args;
|
|
42
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
43
|
+
return "arguments must be a JSON object";
|
|
44
|
+
}
|
|
45
|
+
const obj = value;
|
|
46
|
+
const props = schema?.properties ?? {};
|
|
47
|
+
for (const name of (schema?.required ?? [])) {
|
|
48
|
+
if (obj[name] === undefined || obj[name] === null)
|
|
49
|
+
return `missing required argument "${name}"`;
|
|
50
|
+
}
|
|
51
|
+
for (const [name, prop] of Object.entries(props)) {
|
|
52
|
+
const v = obj[name];
|
|
53
|
+
if (v === undefined || v === null)
|
|
54
|
+
continue;
|
|
55
|
+
if (!matchesAny(v, prop?.type)) {
|
|
56
|
+
const t = Array.isArray(prop.type) ? prop.type.join(" or ") : prop.type;
|
|
57
|
+
return `argument "${name}" must be of type ${t}`;
|
|
58
|
+
}
|
|
59
|
+
if (Array.isArray(v) && prop?.items?.type !== undefined) {
|
|
60
|
+
const bad = v.findIndex((item) => !matchesAny(item, prop.items.type));
|
|
61
|
+
if (bad >= 0)
|
|
62
|
+
return `argument "${name}" item ${bad} must be of type ${prop.items.type}`;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if ("id" in props && obj.id !== undefined && obj.id !== null
|
|
66
|
+
&& (typeof obj.id !== "string" || obj.id.length === 0)) {
|
|
67
|
+
return `argument "id" must be a non-empty string`;
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
/** The arguments without null- or undefined-valued properties: an optional
|
|
72
|
+
* argument given as null is treated as absent (required ones were already
|
|
73
|
+
* checked to be present). Returns {} for absent arguments. */
|
|
74
|
+
export function withoutNullArguments(args) {
|
|
75
|
+
if (typeof args !== "object" || args === null || Array.isArray(args))
|
|
76
|
+
return {};
|
|
77
|
+
const out = {};
|
|
78
|
+
for (const [k, v] of Object.entries(args)) {
|
|
79
|
+
if (v !== null && v !== undefined)
|
|
80
|
+
out[k] = v;
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* mcp-tools.ts — the
|
|
3
|
-
*
|
|
2
|
+
* mcp-tools.ts — the 17 curated flair tools for the Model-2 custom /mcp handler.
|
|
4
3
|
* Curated BY CONSTRUCTION: this module implements a fixed set of tools, each a
|
|
5
4
|
* thin wrapper over the existing flair Resource handler. No business logic is
|
|
6
5
|
* re-implemented — the wrapped handlers (Memory / SemanticSearch /
|
|
@@ -10,7 +9,7 @@
|
|
|
10
9
|
* per-source scoping — see resources/AttentionQuery.ts's module doc), so the
|
|
11
10
|
* MCP surface inherits the SAME security model as the signed-REST path. There
|
|
12
11
|
* is no raw CRUD surface — the only way to reach the datastore through /mcp is
|
|
13
|
-
* via one of these
|
|
12
|
+
* via one of these 17 semantic tools.
|
|
14
13
|
*
|
|
15
14
|
* memory_search · memory_store · memory_update · memory_get · memory_delete ·
|
|
16
15
|
* memory_basement · memory_restore · skill_store · skill_search · skill_get ·
|
|
@@ -363,8 +362,9 @@ function projectSkillCard(r) {
|
|
|
363
362
|
* - the HNSW leg over the stored embedding — which for a skill row IS the
|
|
364
363
|
* `trigger` embedding (#1543), so the task is ranked against "when to use";
|
|
365
364
|
* - the 'query' inputType SemanticSearch already applies to the task string;
|
|
366
|
-
* -
|
|
367
|
-
*
|
|
365
|
+
* - Non-admin searches use resolveReadScope: own records at any visibility
|
|
366
|
+
* plus other agents' non-private records. Administrator searches can
|
|
367
|
+
* include private skills.
|
|
368
368
|
* Identity is the RESOLVED agent; no body agentId is forwarded, so a caller can
|
|
369
369
|
* never widen scope past its own read-scope (the SemanticSearch cross-agent
|
|
370
370
|
* guard would 403 a mismatch anyway).
|
|
@@ -399,9 +399,9 @@ async function skillSearch(agent, args) {
|
|
|
399
399
|
* skill_get — the full skill by id (flair#1546 component 2).
|
|
400
400
|
*
|
|
401
401
|
* A thin wrapper over Memory.get() — the SAME by-id read as memory_get, under
|
|
402
|
-
* the SAME read-scope gate (makeByIdReadGate → resolveReadScope): a non-
|
|
403
|
-
* cannot read another agent's
|
|
404
|
-
* memory does. skill_get is the disclosure step after skill_search's catalog:
|
|
402
|
+
* the SAME read-scope gate (makeByIdReadGate → resolveReadScope): a non-admin
|
|
403
|
+
* caller cannot read another agent's private skill; administrators retain
|
|
404
|
+
* access, exactly as a private memory does. skill_get is the disclosure step after skill_search's catalog:
|
|
405
405
|
* it returns the full procedure (`content`) + trigger + metadata.
|
|
406
406
|
*
|
|
407
407
|
* It is a SKILL tool, not a general reader: a readable id that is NOT a skill
|
|
@@ -542,10 +542,10 @@ async function memoryUpdate(agent, args) {
|
|
|
542
542
|
// retrievable via memory_get and memory_search(includeArchived:true)). Restore
|
|
543
543
|
// is the deliberate, GLOBAL inverse — it un-retires the memory for EVERY
|
|
544
544
|
// session, not a session-local view (that is drawers, Deliverable B, which does
|
|
545
|
-
// not exist yet).
|
|
546
|
-
//
|
|
547
|
-
//
|
|
548
|
-
//
|
|
545
|
+
// not exist yet). Non-admin agent reads use Memory.get()'s owner-and-
|
|
546
|
+
// visibility scope; administrator and trusted internal reads are unfiltered.
|
|
547
|
+
// Mutating another agent's record requires administrator or trusted internal
|
|
548
|
+
// authority (Memory.put()'s stampAttribution gate).
|
|
549
549
|
async function memoryBasement(agent, args) {
|
|
550
550
|
const Cls = await handler("Memory");
|
|
551
551
|
const id = args?.id;
|
|
@@ -597,7 +597,9 @@ async function memoryGet(agent, args) {
|
|
|
597
597
|
// path the Ed25519 REST route takes: it loads the row, hands the override a
|
|
598
598
|
// `RequestTarget` (never a bare string), and still dispatches through
|
|
599
599
|
// Memory.get() → makeByIdReadGate → resolveReadScope, so the scope model is
|
|
600
|
-
// unchanged
|
|
600
|
+
// unchanged: non-admin agents can read their own and other agents'
|
|
601
|
+
// non-private records; administrator reads are unfiltered. See
|
|
602
|
+
// resources/in-process.ts:223.
|
|
601
603
|
//
|
|
602
604
|
// flair#744 slice 1 — opt-in inline trust block. The instance call passed
|
|
603
605
|
// `includeTrust` as a 2nd positional opts arg to get(); the static form has
|
|
@@ -885,7 +887,7 @@ export const TOOLS = bindNativeTools({
|
|
|
885
887
|
memory_search: {
|
|
886
888
|
impl: memorySearch,
|
|
887
889
|
contract: {
|
|
888
|
-
summary: "{ results: MemoryRecord[] } — semantic hits
|
|
890
|
+
summary: "{ results: MemoryRecord[] } — semantic hits subject to the caller's read scope; each hit carries content, never the raw embedding.",
|
|
889
891
|
requiredFields: ["results"],
|
|
890
892
|
fieldTypes: { results: "array" },
|
|
891
893
|
invariants: {
|
|
@@ -921,8 +923,8 @@ export const TOOLS = bindNativeTools({
|
|
|
921
923
|
impl: skillSearch,
|
|
922
924
|
contract: {
|
|
923
925
|
summary: "{ results: SkillCard[] } — the skill catalog (lightweight id/name/trigger/description/tags/agentId, " +
|
|
924
|
-
"ranked by trigger match); the full procedure and the raw embedding are never on a card.
|
|
925
|
-
"
|
|
926
|
+
"ranked by trigger match); the full procedure and the raw embedding are never on a card. Non-admin callers " +
|
|
927
|
+
"can retrieve their own and other agents' non-private skills; administrators can also retrieve private skills.",
|
|
926
928
|
requiredFields: ["results"],
|
|
927
929
|
fieldTypes: { results: "array" },
|
|
928
930
|
invariants: {
|
|
@@ -938,13 +940,14 @@ export const TOOLS = bindNativeTools({
|
|
|
938
940
|
impl: skillGet,
|
|
939
941
|
contract: {
|
|
940
942
|
summary: "The full skill record { id, agentId, content, trigger, tags, durability, metadata, createdAt, ... } for a " +
|
|
941
|
-
"skill readable under the caller's read-scope — embedding + embeddingModel always stripped. A non-
|
|
942
|
-
"cannot read another agent's private skill
|
|
943
|
+
"skill readable under the caller's read-scope — embedding + embeddingModel always stripped. A non-admin " +
|
|
944
|
+
"caller cannot read another agent's private skill; administrators retain access. A readable non-skill id " +
|
|
945
|
+
"is reported as not found.",
|
|
943
946
|
requiredFields: ["id", "agentId", "content", "createdAt"],
|
|
944
947
|
fieldTypes: { id: "string", agentId: "string", content: "string" },
|
|
945
948
|
forbiddenFields: INTERNAL_MEMORY_FIELDS,
|
|
946
949
|
invariants: { fullyResolved: true },
|
|
947
|
-
errorShape: { trigger: "get a non-skill
|
|
950
|
+
errorShape: { trigger: "get a non-skill or unreadable id (404)", fields: ["error", "status"] },
|
|
948
951
|
},
|
|
949
952
|
},
|
|
950
953
|
memory_update: {
|
|
@@ -966,7 +969,7 @@ export const TOOLS = bindNativeTools({
|
|
|
966
969
|
fieldTypes: { id: "string", archived: "boolean" },
|
|
967
970
|
forbiddenFields: INTERNAL_MEMORY_FIELDS,
|
|
968
971
|
invariants: { fullyResolved: true },
|
|
969
|
-
errorShape: { trigger: "basementing a non-existent or
|
|
972
|
+
errorShape: { trigger: "basementing a non-existent, unreadable, or unauthorized id", fields: ["error", "status"] },
|
|
970
973
|
},
|
|
971
974
|
},
|
|
972
975
|
memory_restore: {
|
|
@@ -977,24 +980,24 @@ export const TOOLS = bindNativeTools({
|
|
|
977
980
|
fieldTypes: { id: "string", archived: "boolean" },
|
|
978
981
|
forbiddenFields: INTERNAL_MEMORY_FIELDS,
|
|
979
982
|
invariants: { fullyResolved: true },
|
|
980
|
-
errorShape: { trigger: "restoring a non-existent or
|
|
983
|
+
errorShape: { trigger: "restoring a non-existent, unreadable, or unauthorized id", fields: ["error", "status"] },
|
|
981
984
|
},
|
|
982
985
|
},
|
|
983
986
|
memory_get: {
|
|
984
987
|
impl: memoryGet,
|
|
985
988
|
contract: {
|
|
986
|
-
summary: "The full memory record { id, agentId, content, durability, createdAt, ... } for the caller's
|
|
989
|
+
summary: "The full memory record { id, agentId, content, durability, createdAt, ... } for the requested ID, subject to the caller's read scope; embedding and embeddingModel are stripped by default.",
|
|
987
990
|
requiredFields: ["id", "agentId", "content", "createdAt"],
|
|
988
991
|
fieldTypes: { id: "string", agentId: "string", content: "string" },
|
|
989
992
|
forbiddenFields: INTERNAL_MEMORY_FIELDS,
|
|
990
993
|
invariants: { fullyResolved: true },
|
|
991
|
-
errorShape: { trigger: "get a non-existent
|
|
994
|
+
errorShape: { trigger: "get a non-existent or unreadable id (makeByIdReadGate 404)", fields: ["error", "status"] },
|
|
992
995
|
},
|
|
993
996
|
},
|
|
994
997
|
memory_delete: {
|
|
995
998
|
impl: memoryDelete,
|
|
996
999
|
contract: {
|
|
997
|
-
summary: "Deletes
|
|
1000
|
+
summary: "Deletes a memory by ID when authorized, at any durability tier (success echo is thin). Cross-owner deletion returns { error, status:403 } for a non-admin; a deleted row round-trips as gone via memory_get.",
|
|
998
1001
|
invariants: { fullyResolved: true },
|
|
999
1002
|
errorShape: { trigger: "a non-admin deletes another agent's memory", fields: ["error", "status"] },
|
|
1000
1003
|
},
|
|
@@ -1166,7 +1169,7 @@ export const TOOLS = bindNativeTools({
|
|
|
1166
1169
|
},
|
|
1167
1170
|
},
|
|
1168
1171
|
});
|
|
1169
|
-
/** The tool definitions for a tools/list response (exactly the
|
|
1172
|
+
/** The tool definitions for a tools/list response (exactly the 17 curated tools). */
|
|
1170
1173
|
export function listToolDefs() {
|
|
1171
1174
|
return Object.values(TOOLS).map((t) => t.def);
|
|
1172
1175
|
}
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// runtime (`databases` / `Resource`, storage init) and can't run outside a live
|
|
5
5
|
// Harper; this module has no Harper dependency, so
|
|
6
6
|
// test/unit/memory-consolidate.test.ts exercises the real shipped code.
|
|
7
|
+
import { stripInlinePointerFields } from "./host-source-visibility.js";
|
|
7
8
|
export function parseDuration(s) {
|
|
8
9
|
const m = s.match(/^(\d+)([dhm])$/);
|
|
9
10
|
if (!m)
|
|
@@ -30,7 +31,8 @@ export function parseDuration(s) {
|
|
|
30
31
|
* freshly-created memory is never an archive candidate regardless of retrieval
|
|
31
32
|
* count: archival only considers memories that have had a fair chance to be read.
|
|
32
33
|
*/
|
|
33
|
-
export function evaluate(
|
|
34
|
+
export function evaluate(rawRecord, now, olderThanMs) {
|
|
35
|
+
const record = stripInlinePointerFields(rawRecord);
|
|
34
36
|
const ageMs = record.createdAt ? now - new Date(record.createdAt).getTime() : 0;
|
|
35
37
|
const count = record.retrievalCount ?? 0;
|
|
36
38
|
const lastUse = record.lastRetrieved ?? record.createdAt;
|