Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,14 @@ fixed empty schema, and a target for `toolFilter`), so they are the ones to use
agent actually fetch something and quote it. `slow_update` and `bulk_update` are the annotation-free (write) twins of `slow_lookup` and `bulk`, for specs that put a slow or large write to a person (route `reviewer+person`). `set_note` (a write: no annotations) and `delete_note` (destructive) take `{ note }` and do nothing: they are the targets of the approval reviewer's specs, whose mock reviewer reads the note.

Under `/platform/` it stands in for data-fair's MCP, the built-in server of every autonomous agent with an
identity: `privateMcpUrl` in `api/config/development.js` points there. It serves the data tools only
(`list_road_closures`, `closure_stats`, `export_closures`, `export_my_profile`), renamed `platform_*`, and
its skills under `skill://platform/` — so the built-in server, which wins a name collision, never shadows a
tool of the per-spec fixture, whose call log a spec asserts on. CI starts it too (`reuse-quality.yml`).

Only autonomous agents need it. Without it, every agent with an identity fails with a 502 the moment it
identity and of the back-office assistant: `privateMcpUrl` in `api/config/development.js` points there. It serves
the data tools (`list_road_closures`, `closure_stats`, `export_closures`, `export_my_profile`) and one write
(`set_note`), renamed `platform_*`, and its skills under `skill://platform/` (plus a `notes` skill and a `## Notes` section of its instructions naming only that write, which an assistant's prompt leaves out) — so the built-in server, which
wins a name collision, never shadows a tool of the per-spec fixture, whose call log a spec asserts on. Under
`/platform/datasets/` it stands in for data-fair's datasets MCP, the portal assistant's built-in server:
`list_road_closures`, `closure_stats` and `whoami`, renamed `datasets_*`, and `describe_dataset` under its own name (a page tool name the assistants drop for the MCP one). CI starts it too (`reuse-quality.yml`).

Autonomous agents need it (the personal assistants skip it when it is unreachable). Without it, every agent with an identity fails with a 502 the moment it
gathers its tools — an agent seeded as dev data can then be read but not used, which is a confusing way to
discover this is not running. nodemon restarts it on a change to it or to `tests/support/mcp-fixture.ts`.

Expand Down
5 changes: 5 additions & 0 deletions api/src/agent-session/personal-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ export const personalAgent = (id: string, assistants: PersonalAssistantsConfig):
// consecutive paragraphs of the prompt. The ceiling is stated once, where it is derived from
// the identity rather than from a string every persona has to remember to include.
'You help the person using it with what is on the page in front of them, and with the data they can reach.',
// Judged runs after the switch to MCP reads: on a page showing one dataset the assistant asked the platform
// tools for it by the page's id (not a catalog dataset there), and in the back office it answered « I can only
// read » about rows its edit screen lets it add and correct, never opening that screen.
'What the page shows, its state and its records, is read and changed with the page\'s own tools; any other data tools you have read the rest of the platform.',
'To change something, open its screen, such as the edit page a tool result gives (a dataset\'s editPage), whose own tools then appear: never answer that you can only read when such a screen exists.',
// Every host of these assistants is a data-fair one, so grounding is the product's concern, not a
// host's: a simulation caught the assistant counting rows against a threshold in its own reply,
// contradicting itself, and offering a threshold nobody gave as a figure to quote.
Expand Down
26 changes: 21 additions & 5 deletions api/src/agent-session/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import { nanoid } from 'nanoid'
import type { BrowserToolDescriptor, PageSkillDescriptor, ClientMessage, ServerMessage } from '@agents/shared/agent-session-protocol'
import { HostEventStore } from './host-events.ts'
import { withoutSuperseded } from './superseded-page-tools.ts'

/**
* A socket's sender that can hold back what the turn broadcasts while a page is being caught up.
Expand Down Expand Up @@ -139,10 +140,19 @@ export interface AgentSession {
* end is the only thing that could have answered.
*/
callBrowserTool: (name: string, input: unknown) => Promise<unknown>
/** The page's current contextual tools. Replaced wholesale by `tools-changed`. */
/**
* The page's current contextual tools. Replaced wholesale by `tools-changed`. Without the page reads an MCP
* read supersedes (./superseded-page-tools.ts), unless `keepPageReads` said the turn has no such server.
*/
tools: () => BrowserToolDescriptor[]
/** The page's skills, declared with its tools and replaced with them. */
/** The page's skills, declared with its tools and replaced with them; superseded ones as for `tools`. */
skills: () => PageSkillDescriptor[]
/**
* Whether the coming turns keep the page's reads that data-fair's MCP supersedes: set by the turn, true when it
* reads no built-in server (the portal assistant off a portal, an unreachable server), so the page's own reads
* are its data tools. False until said.
*/
keepPageReads: (keep: boolean) => void
attached: () => boolean
/** Fail everything in flight. Called when the socket closes. */
close: (reason: string) => void
Expand All @@ -168,8 +178,11 @@ export function createAgentSession (options: AgentSessionOptions): AgentSession
// NEXT TURN rather than on the next page load. No answer is no consent.
let reviewConsent = false
let boundTo: string | undefined
// As the page declared them; superseded reads are dropped when read (keepPageReads).
let tools: BrowserToolDescriptor[] = []
let skills: PageSkillDescriptor[] = []
let pageReadsKept = false
const current = () => pageReadsKept ? { tools, skills } : withoutSuperseded(tools, skills)
let attached = false
let closed: string | undefined
const pending = new Map<string, PendingCall>()
Expand Down Expand Up @@ -225,8 +238,9 @@ export function createAgentSession (options: AgentSessionOptions): AgentSession
send,
hostEvents,
chatFactKeys,
tools: () => [...tools],
skills: () => [...skills],
tools: () => [...current().tools],
skills: () => [...current().skills],
keepPageReads: (keep: boolean) => { pageReadsKept = keep },
attached: () => attached,
sessionCookie: () => options.sessionCookie,
siteUrl: () => options.siteUrl,
Expand All @@ -253,6 +267,8 @@ export function createAgentSession (options: AgentSessionOptions): AgentSession
if (!message.conversationId || message.conversationId !== boundTo) hostEvents.clearPending()
return bind(message.conversationId)
case 'tools-changed':
// The page reads that duplicate an MCP read are dropped by tools() and skills(), so every reader of them
// (the model loop, code mode, the approval gate) sees the page without them.
tools = message.tools
skills = message.skills ?? []
return
Expand Down Expand Up @@ -304,7 +320,7 @@ export function createAgentSession (options: AgentSessionOptions): AgentSession
// Only what the page actually advertises. A model that invents a tool name, or a tool that was
// removed by a navigation between the model's decision and this call, must fail here rather than
// be sent to a browser that will never answer.
if (!tools.some(tool => tool.name === name)) {
if (!current().tools.some(tool => tool.name === name)) {
throw new Error(`the page does not offer a tool named ${name}`)
}
const callId = nanoid()
Expand Down
52 changes: 52 additions & 0 deletions api/src/agent-session/superseded-page-tools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* The page tools and skills that duplicate a read of data-fair's MCP, which the personal assistants now read as
* the person (the back office through `/mcp`, the portal through `/datasets/mcp`): dropped from what a page
* declares, so each read has one implementation, the MCP one. The page interactions (navigation, forms,
* filters, selections) and the reads of the page's own unsaved state stay.
*
* Each name was checked against the live listing of both servers, and the links its MCP counterpart returns
* (absolute `page`, Table/Map links: the back office's on the back office, the portal's on a portal). A page
* tool whose read no read-only MCP tool serves is not listed here. Names are dropped whatever page declares
* them, so a name a page uses for something else (the portal's own `list_applications`) is not listed either.
*
* Transitional: the front-ends stop declaring these in their cleanup releases (data-fair, catalogs, portals,
* and the trimmed `@data-fair/agent-tools-data-fair`). Once those releases are deployed everywhere, both lists
* and this filter can go.
*/
import type { BrowserToolDescriptor, PageSkillDescriptor } from '@agents/shared/agent-session-protocol'

export const SUPERSEDED_PAGE_TOOLS: ReadonlySet<string> = new Set([
// datasets (data-fair UI and portal, @data-fair/agent-tools-data-fair): datafair_* on /mcp, the same names on /datasets/mcp
'list_datasets',
'describe_dataset',
// describe_dataset returns the schema on both servers
'get_dataset_schema',
'search_data',
'aggregate_data',
'calculate_metric',
'get_field_values',
// geocode_address on /mcp
'geocode_address',
// applications (data-fair UI): datafair_describe_application
'describe_application',
// catalogs, from data-fair's UI: catalogs_list_catalogs, catalogs_describe_catalog
'list_catalogs',
'describe_catalog',
// catalogs UI: catalogs_list_imports / catalogs_list_publications, catalogs_browse_remote_resources
'list_catalog_items',
'search_remote_catalog'
])

export const SUPERSEDED_PAGE_SKILLS: ReadonlySet<string> = new Set([
// the query skill of @data-fair/agent-tools-data-fair: datafair-workflow on the MCP side
'query-dataset-data',
// data-fair UI: a method over the query tools only, all superseded
'check-data-quality'
])

export function withoutSuperseded (tools: BrowserToolDescriptor[], skills: PageSkillDescriptor[]): { tools: BrowserToolDescriptor[], skills: PageSkillDescriptor[] } {
return {
tools: tools.filter(tool => !SUPERSEDED_PAGE_TOOLS.has(tool.name)),
skills: skills.filter(skill => !SUPERSEDED_PAGE_SKILLS.has(skill.name))
}
}
6 changes: 3 additions & 3 deletions api/src/autonomous-agents/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import mongo from '#mongo'
import config from '#config'
import { type AccountKeys, httpError, reqAdminMode, reqSessionAuthenticated, assertAccountRole } from '@data-fair/lib-express'
import type { Request } from 'express'
import { listMcpServerCatalog, personSiteCredentials, unknownMcpServerIds, PLATFORM_MCP_SERVER_ID, getsPlatformServer, type SiteCredentials, type McpServerRef } from '../mcp-servers/operations.ts'
import { listMcpServerCatalog, personSiteCredentials, unknownMcpServerIds, isBuiltInServerId, platformMcpServer, getsPlatformServer, type SiteCredentials, type McpServerRef } from '../mcp-servers/operations.ts'
import { getAgentToken, agentSiteCredentials, forgetAgentSessions, listAccountSites, type EnrolledAutonomousAgent } from '../nhi/service.ts'
import { credentialClaims, autonomousAgentSubject } from '../nhi/operations.ts'
import { listAutonomousAgentToolDescriptors, type AutonomousAgentForTools, type SkippedServer } from '../mcp-servers/client.ts'
Expand Down Expand Up @@ -184,8 +184,8 @@ export const describeAutonomousAgentTools = async (autonomousAgent: AutonomousAg
? await agentSiteCredentials(autonomousAgent)
: personSiteCredentials(undefined, undefined)
// `kind` as a turn records it (shared/tool-source.ts), so the chat's inspection dialog groups both alike.
const { descriptors } = await listAutonomousAgentToolDescriptors(autonomousAgent, sites, { platform: getsPlatformServer(autonomousAgent, platformMcpUrlOf(autonomousAgent.id)) ? platformMcpUrlOf(autonomousAgent.id) : undefined })
const results = descriptors.map(descriptor => ({ ...descriptor, kind: descriptor.server === PLATFORM_MCP_SERVER_ID ? 'platform' as const : 'catalog' as const }))
const { descriptors } = await listAutonomousAgentToolDescriptors(autonomousAgent, sites, { builtIn: getsPlatformServer(autonomousAgent, platformMcpUrlOf(autonomousAgent.id)) ? platformMcpServer(platformMcpUrlOf(autonomousAgent.id)) : undefined })
const results = descriptors.map(descriptor => ({ ...descriptor, kind: isBuiltInServerId(descriptor.server) ? 'platform' as const : 'catalog' as const }))
if (!autonomousAgent.externalMcpServers?.length) return { results, skipped: [] as SkippedServer[] }
const external = await listExternalToolDescriptors(autonomousAgent.externalMcpServers, { publicIps: envPublicIps() })
return { results: [...results, ...external.descriptors.map(descriptor => ({ ...descriptor, kind: 'external' as const }))], skipped: external.skipped }
Expand Down
2 changes: 1 addition & 1 deletion api/src/code-mode/code-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ export const codeFacingTools = (opts: { names: string[], fixed: ToolSet, page: R
if (!base?.execute || !codeCallable(name, sourced?.tool ?? base, { person })) continue
const execute = base.execute
// Who decides this tool's calls when a person can: the reviewer first for a reviewed tool, the person for a tool
// asking by its own needsApproval (the personal assistant's writes).
// asking by its own needsApproval (the loop's own service tools; the personal assistant's MCP tools are read-only).
const asksFirst = person && (sourced?.review || (sourced?.tool ?? base).needsApproval)
out[name] = {
...base,
Expand Down
44 changes: 35 additions & 9 deletions api/src/code-mode/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,25 +224,44 @@ export const nameToolResultType = (packageDescription: string, rendered: string)
.replace('declare const tools: {', `type ${TOOL_RESULT_TYPE} = ${rendered.replace(/\n {2}/g, '\n')};\ndeclare const tools: {`)
}

export const describeScriptTool = (packageDescription: string, opts: { reviewed?: boolean, timeoutMs?: number, person?: boolean } = {}): string => {
/**
* What the turn offers that code_mode's description speaks of, so it names only what is there: the direct-only
* tools of the turn (directOnlyNames), whether a tool asks the person (an approval), and whether it has files
* (read_file). A personal assistant's turn has none of these, and its description says nothing of them.
*/
export interface ScriptToolOffer {
approvals?: boolean
files?: boolean
directOnly?: string[]
}

export const describeScriptTool = (packageDescription: string, opts: { reviewed?: boolean, timeoutMs?: number, person?: boolean } & ScriptToolOffer = {}): string => {
const head = packageDescription.split('\nTool call examples:')[0].trimEnd()
const directOnly = [...(opts.approvals && !opts.person ? ['Tools that need approval'] : []), ...(opts.directOnly ?? [])]
return [
head,
PAPA_DECLARATION,
'console.log output is returned after the result. A tool failure is an exception carrying the tool\'s message.',
'What a tool returns: an MCP tool returns its structured result as an object when it has one, otherwise its text as a string (JSON.parse it if it is JSON). A tool whose result carries files returns { text, files: [{ file_path, mimeType, size, sha256, etag?, lastModified? }] }, where `text` only describes the files: read their content with read_file(files[0].file_path). read_file returns the whole text of the file.',
'Check what you got before writing or importing it: a parse that yields nothing should throw, not write an empty file.',
'Have the script read its data itself (call the tool, read_file the path it returned), never paste in what an earlier call showed you: the script must work on what is there when it runs.',
`Everything a script passes to and gets from its tools counts toward ${transferLimit}; a larger file belongs in a tool that takes the file itself.`,
opts.files
? 'What a tool returns: an MCP tool returns its structured result as an object when it has one, otherwise its text as a string (JSON.parse it if it is JSON). A tool whose result carries files returns { text, files: [{ file_path, mimeType, size, sha256, etag?, lastModified? }] }, where `text` only describes the files: read their content with read_file(files[0].file_path). read_file returns the whole text of the file.'
: 'What a tool returns: an MCP tool returns its structured result as an object when it has one, otherwise its text as a string (JSON.parse it if it is JSON).',
...(opts.files ? ['Check what you got before writing or importing it: a parse that yields nothing should throw, not write an empty file.'] : []),
opts.files
? 'Have the script read its data itself (call the tool, read_file the path it returned), never paste in what an earlier call showed you: the script must work on what is there when it runs.'
: 'Have the script read its data itself (call the tool), never paste in what an earlier call showed you: the script must work on what is there when it runs.',
opts.files
? `Everything a script passes to and gets from its tools counts toward ${transferLimit}; a larger file belongs in a tool that takes the file itself.`
: `Everything a script passes to and gets from its tools counts toward ${transferLimit}.`,
'Dates: a script\'s local time zone is the server\'s, not the task\'s. Work in UTC: a date-only string ("2026-10-21") is UTC midnight, so compare YYYY-MM-DD strings, or give every date-time a trailing Z; new Date("2026-10-14T00:00:00") without Z is the server\'s local midnight.',
opts.person
? 'wait_for_user_action, the access and planning requests and read_skill can only be called directly.'
: 'Tools that need approval, wait_for_user_action, the access and planning requests and read_skill can only be called directly.',
...(opts.person ? [pausedScriptNote] : []),
...(directOnly.length ? [`${listOf(directOnly)} can only be called directly.`] : []),
...(opts.person && opts.approvals ? [pausedScriptNote] : []),
...(opts.reviewed ? [reviewedScriptNote(opts.timeoutMs ?? CODE_MODE_POLICY.timeoutMs)] : [])
].join('\n\n')
}

/** "a", "a and b", "a, b and c". */
const listOf = (items: string[]) => items.length > 1 ? `${items.slice(0, -1).join(', ')} and ${items.at(-1)}` : items[0]

/**
* Tools a script may NOT call, whatever the turn offers (spec §6.3, plan 4 decision 4): the handover ends the
* turn; the access and planning requests ask an administrator; read_skill is guidance for the model, which in a
Expand All @@ -252,6 +271,13 @@ export const describeScriptTool = (packageDescription: string, opts: { reviewed?
*/
const DIRECT_ONLY = new Set([WAIT_TOOL_NAME, 'request_web_access', 'request_mcp_access', 'plan_task', 'update_task', 'delete_task', 'read_skill', 'load_tools', CODE_MODE_TOOL_NAME])

/**
* The turn's tools a script cannot call, as code_mode's description names them: load_tools and code_mode itself go
* without saying. Only those the turn offers — an assistant's turn has no planning nor access request to name.
*/
export const directOnlyNames = (names: string[]): string[] =>
names.filter(name => DIRECT_ONLY.has(name) && name !== 'load_tools' && name !== CODE_MODE_TOOL_NAME)

/**
* A script's tool input without the keys that pollute a prototype: `__proto__`, and a `constructor` carrying a
* `prototype` (what secure-json-parse removes). The bridge hands a tool the script's JSON, where `__proto__` is
Expand Down
Loading
Loading