Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
15 changes: 15 additions & 0 deletions .changeset/34689-slim-mcp-tool-list.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@objectstack/mcp': patch
'@object-ui/console': patch
---

fix(mcp): the open MCP door's `tools/list` is a quarter smaller; teaching prose moves to the served SKILL.md

Clause-②: no
Metadata-protocol: none

Every MCP connection pays for `tools/list` before any work starts. Its total for an API key on a self-hosted app (17 tools) drops from 47,712 to 36,481 bytes; the descriptions `@objectstack/mcp` owns drop from 18,213 to about 8,740. No tool is removed or renamed, and nothing a tool accepts changes: only description strings.

Each description keeps what a call needs: the arguments, the confirmation a destructive call takes, the refusal it may answer and what to do about it. Worked examples, answer-reading guidance and edge cases move to the SKILL.md the server serves at `/api/v1/mcp/skill` (and the Console's "Download skill" copy of it): `describe_object`'s field facts, `query_records`' `latestPer` / `expand` examples (its approvals-waiting-on-you filter and the `sys_user` colleague lookup stay in the description, one line each), `aggregate_records` under the `query_records` entry, `get_record`'s `related`, `run_action`'s `FLOW_FAILED` relay, and `create_upload_link`'s read-only and locked-record cases. `validate_expression`'s description now names the facts to pass per site and points at the skill for the full list of checks.

The skill's `validate_expression` entry now names its `variables` input, and says that at a `flow_condition` the shadowed-read warning, and the binding of a bare name to the variable rather than the field, need it.
9 changes: 4 additions & 5 deletions packages/mcp/src/mcp-action-refusal-details.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ describe('run_action / resume_run over HTTP /mcp: a failed flow run names the re
});
}

it('the run_action and resume_run descriptions teach the same read order', async () => {
it('the run_action and resume_run descriptions point at the second text block', async () => {
const body = { jsonrpc: '2.0', id: nextId++, method: 'tools/list', params: {} };
const runtime = new MCPServerRuntime({ name: 'pin', version: '0.0.0' });
const res = await runtime.handleHttpRequest(
Expand All @@ -283,10 +283,9 @@ describe('run_action / resume_run over HTTP /mcp: a failed flow run names the re
);
const tools = (JSON.parse(await res.text()) as { result: { tools: Array<{ name: string; description: string }> } })
.result.tools;
const runAction = tools.find((t) => t.name === 'run_action')!.description;
const order = ['details.errorMessage', 'userMessage', 'details.innerRefusal.message'].map((m) => runAction.indexOf(m));
expect(order.every((i) => i >= 0), runAction).toBe(true);
expect([...order].sort((a, b) => a - b)).toEqual(order);
// [#34689] The read order is the answer's: the second block carries the
// reason already chosen (pinned above), so each description only points at it.
expect(tools.find((t) => t.name === 'run_action')!.description).toContain('second text block');
expect(tools.find((t) => t.name === 'resume_run')!.description).toContain('second text block');
});
});
308 changes: 92 additions & 216 deletions packages/mcp/src/mcp-http-tools.ts

Large diffs are not rendered by default.

21 changes: 7 additions & 14 deletions packages/mcp/src/mcp-system-object-ai-read.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,19 +172,12 @@ describe('everything else about system objects stays refused (#32442)', () => {
});
});

describe('the query tool names the "pending for me" filter shape (#32442)', () => {
it('query_records text carries the My Pending filter on sys_approval_request', async () => {
const body = { jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} };
const runtime = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' });
const req = new Request('http://localhost/api/v1/mcp', {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
body: JSON.stringify(body),
});
const res = await runtime.handleHttpRequest(req, { bridge: makeBridge(attestsOne), parsedBody: body });
const tools = ((await res.json()) as any).result.tools as Array<{ name: string; description: string }>;
const description = tools.find((t) => t.name === 'query_records')?.description ?? '';
expect(description).toContain('"sys_approval_request"');
expect(description).toContain('{"status":"pending","pending_approvers":{"$contains":"{current_user_id}"}}');
describe('the served skill names the "pending for me" filter shape (#32442)', () => {
it('SKILL.md carries the My Pending filter on sys_approval_request', () => {
// [#34689] Moved from query_records' tool text to the served skill: a
// worked example is teaching, which a client reads when it needs it.
const skill = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' }).renderSkill();
expect(skill).toContain('`sys_approval_request`');
expect(skill).toContain('{"status":"pending","pending_approvers":{"$contains":"{current_user_id}"}}');
});
});
55 changes: 45 additions & 10 deletions packages/mcp/src/skill-md.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,11 @@ const UPLOAD_LINK_TOOL_LINES = `- **create_upload_link({ objectName, recordId, f
Give the link to the user to open where they are signed in to this
deployment; it works only for them, once, for that record and field only,
and expires at \`expiresAt\`. The upload is stored as the user, so they
must be able to edit the record.
must be able to edit the record. A field link also needs a field they may
write: none is made for a read-only field (\`readonly\`, or \`readonlyWhen\`
on this record) or a record a pending approval locks, which still takes
attachments. An upload refused when it arrives attaches nothing and answers
the reason.
`;

/**
Expand Down Expand Up @@ -425,8 +429,14 @@ create/update payload.

- **list_objects()** — list available objects. System \`sys_*\` objects are hidden,
except the few declared readable by agents, such as \`sys_user\` (read only).
- **describe_object({ objectName })** — an object's fields and features.
- **validate_expression({ objectName, expression, site?, severity?, triggerKind?, sweepObject?, startCondition?, field? })** — check a CEL
- **describe_object({ objectName })** — an object's fields and features. A
\`readonly\` field is never set in a write (a computed value or a declared
read-only field); \`readonly\` is the schema's, not your edit permission, so a
write naming a field you may not edit is refused. Send an option's \`value\`.
To get a \`defaultValue\`, omit the field: a token (\`NOW()\`, \`current_user\`)
or an expression object is never copied. A validation's \`message\` is what a
refused write answers.
- **validate_expression({ objectName, expression, site?, severity?, triggerKind?, sweepObject?, startCondition?, variables?, field? })** — check a CEL
expression against an object's schema *before* you author it into a formula,
validation, or flow condition. Returns build-time errors (bare field refs,
unknown fields/functions; at a \`formula\` or \`validation\` site, every other
Expand All @@ -436,7 +446,8 @@ create/update payload.
an unguarded nullable field or a read of \`parent\`; at a \`flow_condition\`
of a record-triggered flow, an unguarded nullable \`record.\`/\`previous.\`
read) and advisory warnings
(text/boolean fields misused in arithmetic; an error at a \`validation\` site,
(text/boolean fields misused in arithmetic; date-equality pitfalls; an error
at a \`validation\` site,
worded for the rule's \`severity\`, and at a \`flow_condition\` of a
record-triggered or time-relative flow, where it fails the run; a warning on
any other flow; at a \`formula\`, \`validation\` or \`flow_condition\` site,
Expand All @@ -455,13 +466,32 @@ create/update payload.
At a \`flow_condition\` the verdict is the runtime publish gate's, the one a
flow saved through MCP meets: \`os validate\` also judges bare names and
unbound roots over the whole flow, so write \`record.<field>\`, and pass the
flow's \`startCondition\` for an edge or \`decision\` condition after it. Pass
\`field\` (formula) to be judged as that field: its type, and the formula
flow's \`startCondition\` for an edge or \`decision\` condition after it, and
its declared \`variables\`: the shadowed-read warning, and the binding of a
bare name to the variable rather than the field, need them at a
\`flow_condition\`. Pass \`field\` (formula) to be judged as that field: its type, and the formula
cycle it would close; a field not yet declared is judged as a new formula.
- **query_records({ objectName, where?, fields?, limit?, offset?, orderBy? })** —
- **query_records({ objectName, where?, fields?, limit?, offset?, orderBy?, expand?, latestPer? })** —
read records. \`where\` is a field→value match, e.g. \`{ "status": "open" }\`.
Results are page-capped; use \`limit\`/\`offset\` to page.
- **get_record({ objectName, recordId })** — fetch one record by id.
Results are page-capped; use \`limit\`/\`offset\` to page. The answer's
\`source\` names the object, filter, measures and grouping its figures came
from; \`source.line\` is that source in the user's language. For "each X with
its latest Y", \`latestPer: { "by": ["account"], "orderBy": [{ "field":
"close_date", "order": "desc" }] }\` answers one record per group (ties go by
id). \`expand: ["account"]\` returns a lookup as the record it names; a field
whose object this door does not serve you refuses the call. For counts,
sums and breakdowns, \`aggregate_records({ objectName, aggregations,
groupBy?, where?, orderBy?, limit? })\` computes them in the database where
it is offered: groups of a select field come in the field's option order,
an amount over one fixed currency names its ISO 4217 code in \`currencies\`,
and a lookup group carries \`<key>__label\`, the record's name: name the group
by it, and where it has none, say the record cannot be named rather than
quoting the id.
- **get_record({ objectName, recordId, related? })** — fetch one record by id.
\`related: [{ "object": "crm_opportunity" }]\` adds up to 3 lists of the
records that point at it (name \`field\` when the child points here through
several fields), each under your permissions on that object; a list with
\`truncated: true\` has more rows.
- **create_record({ objectName, data })** — create a record.
- **update_record({ objectName, recordId, data })** — change fields on a record.
- **delete_record({ objectName, recordId, confirm })** — delete a record.
Expand Down Expand Up @@ -519,7 +549,8 @@ create/update payload.
account's own key (an agent acting for itself, for no person) the call is
refused whatever it sends and nothing runs: hand the action to a person, or
its author declares \`ai.requiresConfirmation: false\` when it is safe
unattended.
unattended. A flow action that fails answers \`FLOW_FAILED\`: tell the user
the reason its second text block gives, never the flow and node chain.
- **resume_run({ runId, values? })** — continue a flow run that
\`run_action\` answered with \`status: "paused"\` and a \`screen\` (a form the
flow needs filled in). Send the screen's field values in \`values\`, keyed by
Expand Down Expand Up @@ -549,6 +580,10 @@ ${renderFileToolLines(options)}${renderDatasetToolLines(options)}${options.feder
share a name, tell them apart by email, and ask your human which one if
unsure. You see the colleagues your console's person picker shows you (your
organization, directory fields), and \`sys_user\` is read only.
- **Approvals waiting on you.** Where the app runs approvals, query
\`sys_approval_request\` with
\`where: {"status":"pending","pending_approvers":{"$contains":"{current_user_id}"}}\`
(\`{current_user_id}\` stands for you), and decide one with \`run_action\`.
- **Prefer actions over hand-edits.** When \`list_actions\` offers an action for
the task (approve, convert, close, …), call it instead of updating the
records yourself — actions carry the app's validation and side effects.
Expand Down
115 changes: 115 additions & 0 deletions packages/mcp/src/tools-list-weight-34689.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#34689] What the open door's `tools/list` costs: every connection pays it,
* in the client's own tokens, before any work starts.
*
* The surface is the one a self-hosted app serves an API key (no scope list):
* object CRUD with `aggregate_records`, the action trio, the file pair and the
* dataset pair — the dataset descriptions are the service-analytics
* definitions the runtime hands the bridge. It is read through the real
* registration path (a `tools/list` round-trip), never from a list of names.
*
* The run prints one row per tool (description bytes, input-schema bytes) and
* the response total, so the before/after table a PR on this surface owes is
* one command away:
*
* pnpm --filter @objectstack/mcp exec vitest run src/tools-list-weight-34689.test.ts
*
* The ceiling is the slimmed total with headroom for one more tool's worth of
* text. Teaching prose belongs in the served SKILL.md (`skill-md.ts`), which a
* client reads when it needs it; a description carries what the call needs.
*/

import { describe, it, expect } from 'vitest';
import { getDatasetToolDefinitions } from '@objectstack/service-analytics';

import { MCPServerRuntime } from './mcp-server-runtime.js';
import type { McpDataBridge, McpActionBridge } from './mcp-http-tools.js';
import type { McpFileBridge } from './file-content.js';

/** Every member the open door's API-key surface registers a tool for, all stubbed. */
function makeFullBridge(): McpDataBridge & McpActionBridge & McpFileBridge {
return {
async listObjects() { return []; },
async describeObject() { return null; },
async query() { return { records: [] }; },
async get() { return null; },
async create() { return {}; },
async update() { return {}; },
async remove() { return {}; },
async aggregate() { return []; },
async listActions() { return []; },
async runAction() { return {}; },
async resumeRun() { return {}; },
async listRecordFiles() { return []; },
async readRecordFile() {
return { fileId: 'f', name: 'f', mimeType: null, size: null, maxBytes: 0, download: null };
},
async createUploadLink() {
return { url: 'https://x.test/u', expiresAt: '2026-01-01T00:00:00.000Z' };
},
// The runtime bridge serves it where storage can mint a link for a record
// not yet created; it adds text to create_upload_link, so it is measured.
async createUploadLinkForNewRecord() {
return { url: 'https://x.test/u', expiresAt: '2026-01-01T00:00:00.000Z', fileIds: ['f'] };
},
async listDatasets() { return { datasets: [] }; },
async queryDataset() { throw new Error('not called'); },
datasetToolDefinitions() { return getDatasetToolDefinitions(); },
};
}

interface ToolRow { name: string; description: number; inputSchema: number }

async function measureToolsList(): Promise<{ total: number; rows: ToolRow[] }> {
const runtime = new MCPServerRuntime({ name: 'objectstack', version: '0.0.0' });
const body = { jsonrpc: '2.0', id: 1, method: 'tools/list' };
const res = await runtime.handleHttpRequest(
new Request('http://localhost/api/v1/mcp', {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
body: JSON.stringify(body),
}),
{ bridge: makeFullBridge(), parsedBody: body },
);
const text = await res.text();
const tools: Array<{ name: string; description?: string; inputSchema?: unknown }> = JSON.parse(text).result.tools;
const rows = tools.map((t) => ({
name: t.name,
description: Buffer.byteLength(t.description ?? ''),
inputSchema: Buffer.byteLength(JSON.stringify(t.inputSchema ?? {})),
}));
return { total: Buffer.byteLength(text), rows };
}

/**
* The slimmed total (36,481 bytes, from 47,712) plus room for one more tool. A PR
* that needs more raises it beside its own before/after table.
*/
const TOOLS_LIST_BYTE_CEILING = 38_000;

describe('[#34689] the open door tools/list weight', () => {
it('prints the per-tool table and stays under the ceiling', async () => {
const { total, rows } = await measureToolsList();
// Sanity: the harness sees the whole API-key surface, or the number measures nothing.
expect(rows.map((r) => r.name)).toEqual(expect.arrayContaining([
'list_objects', 'describe_object', 'validate_expression', 'query_records', 'aggregate_records',
'get_record', 'create_record', 'update_record', 'delete_record', 'delete_records',
'list_actions', 'run_action', 'resume_run', 'read_file', 'create_upload_link',
'list_datasets', 'query_dataset',
]));

const sorted = [...rows].sort((a, b) => (b.description + b.inputSchema) - (a.description + a.inputSchema));
const lines = sorted.map((r) => `| ${r.name} | ${r.description} | ${r.inputSchema} | ${r.description + r.inputSchema} |`);
const sum = (k: 'description' | 'inputSchema') => rows.reduce((n, r) => n + r[k], 0);
console.log([
`tools/list: ${rows.length} tools, ${total} bytes (descriptions ${sum('description')}, input schemas ${sum('inputSchema')})`,
'| tool | description | input schema | both |',
'|:--|--:|--:|--:|',
...lines,
].join('\n'));

expect(total).toBeLessThanOrEqual(TOOLS_LIST_BYTE_CEILING);
});
});
Loading
Loading