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
19 changes: 19 additions & 0 deletions .changeset/35442-mcp-app-docs-tools.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
'@objectstack/mcp': patch
'@objectstack/runtime': patch
'@objectstack/spec': patch
---

feat(mcp): the MCP door can search and read the installed apps' manuals, and tells the client how to answer a question about the app

Clause-②: yes
Metadata-protocol: none

An AI client connected over MCP (a user's own Claude, Cursor, …) can now answer "what is X?" and "how does this approval work?" from the manuals the installed apps ship, instead of from its own guess:

- **`search_package_docs({ terms, package? })`** finds the pages whose title, a heading or text contains one of the terms (case aside, in the page's base text or a translation). Pages that contain more of the terms come first, then pages where the terms sit higher (the sum of title 3, heading 2, text 1), then by title; at most 10, each with an excerpt, its manual and, where the page has one, its console address (`/_console/apps/<package>/docs/<book>/<page>`) to cite. The heading parse is line-based and linear.
- **`read_package_doc({ name, package?, locale? })`** reads one page: its title, manual, Markdown content and, where the page has one, its console address (cut at 60,000 characters, and the answer says so).
- **Who sees what.** Both tools read the `doc` items through the `/meta/doc` docs-audience gate (ADR-0046 §6.7) with the request's execution context as the caller: a page the caller may not read is neither found nor read, and answers as not found. On an OAuth grant that caller is the agent, so the docs audience is judged on the token's grant (its scope-derived permission sets), not on the person's own permission sets: a manual whose audience is a permission set the person holds stays hidden on that connection. Both tool descriptions say so. Both are read tools: they register for an API key, a session, or a token granted `data:read`. The runtime's HTTP bridge carries them where the protocol serves the `/meta` list read; the stdio bridge does not.
- **The answer order.** Where both tools register, the HTTP `initialize` instructions say: read the manuals first; answer a concept from the manual, and label a general explanation as one when no page covers it; for a process or rule, also read its real definition, which wins where the two differ; end with each page's title and url. The rule names a definition reader only where the connection lists one (`describe_metadata`, else `get_metadata_item`, both under `metadata:write`); without one it says to answer from the manual and state that the configured process was not checked. A host's own instructions and a configured `instructions` option are served unchanged.

The two names are the ones the cloud AI runtime already registers, so `MCP_DOOR_TOOL_NAMES` (`@objectstack/spec/system`) now lists them too; `PLATFORM_PROVIDED_TOOL_NAMES` is unchanged. No metadata key, value or default changes.
24 changes: 22 additions & 2 deletions packages/mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,16 @@ grant, then two parts:
with `candidates` in the answer is the same question, never a match; no match
and no candidates falls back to the object tools and says the answer is not
from a governed metric. A grant without `data:read` gets no such sentence.
- **The answer-order rule**, only where this request registers both
`search_package_docs` and `read_package_doc`: read the installed apps'
manuals before answering; a concept is answered from the manual, and a
general explanation says the manuals do not cover it; a process or rule is
read in the manual and in its real definition, the definition winning where
the two differ; the answer ends with each page's title and url. It names a
definition reader only where the connection lists one (`describe_metadata`,
else the open draft door's `get_metadata_item`, both under `metadata:write`);
without one it says to answer from the manual and state that the configured
process was not checked.
- **The skills install line**: `Published skills: @objectstack/skills <version>`
and the command that installs it into the agent's skills directory with or
without a project, `os skills install --version <version>` (with its
Expand Down Expand Up @@ -155,17 +165,27 @@ apply):
// Governed metrics (ADR-0149)
'list_datasets' // Governed datasets: measures and dimensions, with labels, synonyms and exact matches
'query_dataset' // Compute a governed metric; the answer carries its provenance

// App manuals (the installed packages' docs)
'search_package_docs' // Pages whose title, a heading or text contains a term; ≤10, more terms first, with excerpt and console url where the page has one
'read_package_doc' // One page by name: title, manual, Markdown content, console url where the page has one
```

`aggregate_records` is registered only when the bridge implements `aggregate`,
`resume_run` only when it implements `resumeRun`, and `list_datasets` /
`query_dataset` only when it implements all three of `listDatasets`,
`queryDataset` and `datasetToolDefinitions` (the runtime's bridge does where the
analytics service serves its dataset executor); a bridge without those seams
analytics service serves its dataset executor), and `search_package_docs` /
`read_package_doc` only when it implements both `searchPackageDocs` and
`readPackageDoc` (the runtime's HTTP bridge does where the protocol serves the
`/meta` list read; it reads every page through the `/meta/doc` docs-audience
gate as the caller, so a page the caller may not read is neither found nor
read; on an OAuth grant the caller is the agent, judged on the token's grant
rather than the person's own permission sets; the stdio bridge carries neither); a bridge without those seams
serves the rest and advertises nothing it cannot do.

OAuth scopes narrow the families at consent time: `data:read` covers
list/describe/query/aggregate/get and the dataset pair, `data:write` covers create/update/delete, and
list/describe/query/aggregate/get, the dataset pair and the app-docs pair, `data:write` covers create/update/delete, and
`actions:execute` covers `list_actions` / `run_action` / `resume_run`. `delete_records` needs both
`data:read` and `data:write`: its preview reads the selection's ids and count. A tool outside the grant
is **not registered at all**, so the SDK rejects it as an unknown tool — the
Expand Down
2 changes: 2 additions & 0 deletions packages/mcp/src/mcp-file-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,8 @@ describe('the tools the door registers are the ones a skill offered over MCP may
{ name: 'list_datasets', description: 'List the datasets.' },
{ name: 'query_dataset', description: 'Query one metric of a dataset.' },
],
searchPackageDocs: unused,
readPackageDoc: unused,
});
}
const everyScope = [
Expand Down
228 changes: 228 additions & 0 deletions packages/mcp/src/mcp-http-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,83 @@ export interface McpDataBridge {
* holds no second copy of it. OPTIONAL — see {@link listDatasets}.
*/
datasetToolDefinitions?(): ReadonlyArray<Pick<AIToolDefinition, 'name' | 'description'>>;
/**
* [#35442] `search_package_docs`: the installed apps' manual pages (their
* `doc` items) whose title, a heading or text contains one of
* `input.terms`, ranked and capped at `opts.maxResults`. Runs AS the
* principal: the host reads the docs through the ADR-0046 §6.7 docs-audience
* gate, so a page the caller may not read is never searched. On an OAuth
* grant the principal is the agent envelope, judged on the token's grant.
*
* OPTIONAL: a host that cannot read docs for the caller omits both doc
* members ({@link searchPackageDocs}, {@link readPackageDoc}) and neither
* doc tool registers. The pair registers only when both are present
* (`registerPackageDocTools`).
*/
searchPackageDocs?(input: SearchPackageDocsInput, opts: { maxResults: number }): Promise<SearchPackageDocsOutput>;
/**
* [#35442] `read_package_doc`: one manual page by name, as this caller may
* read it, or a coded refusal (a page the caller may not read answers as
* not found). OPTIONAL — see {@link searchPackageDocs}.
*/
readPackageDoc?(input: ReadPackageDocInput): Promise<ReadPackageDocOutput>;
}

/** [#35442] Where a manual page lives: its name, app, title, manual and the console address to cite. */
export interface McpPackageDocAddress {
/** The page's name: what `read_package_doc` takes. */
name: string;
/** The app (package) that ships the page. */
package?: string;
/** The page's title, in the locale it was read or matched in. */
title: string;
/** The manual (book) the page opens in. */
book?: { name: string; label?: string };
/** The console address of the page (`/_console/apps/PACKAGE/docs/BOOK/NAME`), to cite as the source. */
url?: string;
}

/** [#35442] One `search_package_docs` hit. */
export interface McpPackageDocHit extends McpPackageDocAddress {
/** The best place a term was found: the title, a heading, or the text. */
matchedOn: 'title' | 'heading' | 'text';
/** The terms this page contains. */
matchedTerms: string[];
/** The heading a term was found under or in, when there is one. */
heading?: string;
/** A short passage around the first match. */
excerpt: string;
/** The translation the match was found in, when it was not the page's base text. */
locale?: string;
}

/** [#35442] `search_package_docs` input. */
export interface SearchPackageDocsInput {
terms: string[];
package?: string;
}

/** [#35442] `search_package_docs` answer. */
export interface SearchPackageDocsOutput {
terms: string[];
results: McpPackageDocHit[];
/** More pages matched than `results` carries. */
truncated: boolean;
}

/** [#35442] `read_package_doc` input. */
export interface ReadPackageDocInput {
name: string;
package?: string;
locale?: string;
}

/** [#35442] `read_package_doc` answer: the page's Markdown content and where it lives. */
export interface ReadPackageDocOutput extends McpPackageDocAddress {
description?: string;
/** The translation served, when it was not the page's base text. */
locale?: string;
content: string;
}

export interface RegisterObjectToolsOptions {
Expand Down Expand Up @@ -3061,6 +3138,9 @@ export function wireBridgeTools(
// [ADR-0149 D2] `list_datasets` / `query_dataset`, only where the bridge
// carries all three dataset members and the grant admits `data:read`.
registered.push(...registerDatasetTools(server, bridge, options));
// [#35442] `search_package_docs` / `read_package_doc`, only where the bridge
// carries both doc members and the grant admits `data:read`.
registered.push(...registerPackageDocTools(server, bridge, options));
return registered;
}

Expand Down Expand Up @@ -3200,6 +3280,154 @@ export function registerDatasetTools(
return registered;
}

/** [#35442] The app-docs search tool's name, the one the cloud `service-ai` registry already holds. */
export const SEARCH_PACKAGE_DOCS_TOOL_NAME = 'search_package_docs';

/** [#35442] The app-docs read tool's name, the one the cloud `service-ai` registry already holds. */
export const READ_PACKAGE_DOC_TOOL_NAME = 'read_package_doc';

/** [#35442] The most pages one `search_package_docs` answer lists; its description states it. */
export const PACKAGE_DOC_SEARCH_MAX_RESULTS = 10;

/**
* [#35442] The most characters of a page `read_package_doc` returns. A longer
* page answers its first part and says it was cut, rather than an answer no
* client can hold.
*/
export const READ_PACKAGE_DOC_MAX_CHARS = 60_000;

/**
* [#35442] Whether this bridge and grant register BOTH doc tools: the bridge
* carries both doc members and the grant is the read family's
* (`aggregate_records`'s: an undefined grant keeps them, a scope list without
* `data:read` registers neither). The one gate: `registerPackageDocTools`
* registers from it, and `handleHttpRequest` reads it to decide whether the
* `initialize` instructions carry the answer-order rule, so the rule is sent
* exactly where `tools/list` lists both tools.
*/
export function packageDocToolsServed(
bridge: Partial<McpDataBridge> | undefined,
options: RegisterObjectToolsOptions = {},
): boolean {
if (!bridge) return false;
if (typeof bridge.searchPackageDocs !== 'function' || typeof bridge.readPackageDoc !== 'function') return false;
const scopes = options.grantedScopes;
return !scopes || scopes.includes(MCP_OAUTH_SCOPE_DATA_READ);
}

/**
* [#35442] Register the app-docs pair over the bridge's doc members:
* `search_package_docs` finds the installed apps' manual pages that contain a
* business word, and `read_package_doc` reads one page.
*
* - **No second gate.** Neither tool judges what the caller may read: the
* host's members read the `doc` items through the `/meta/doc` docs-audience
* gate (ADR-0046 §6.7) as the principal, so a page the caller may not read
* is neither found nor read, and reads as not found. On an OAuth grant the
* principal is the agent envelope, so the docs audience is judged on the
* token's grant, not the person's own permission sets; both descriptions
* say so.
* - **The search is a substring match**, stated in the description: no
* server-side doc search exists, so the honest search is a term found in a
* page's title, a heading or its text (case aside). Pages that contain more
* of the terms come first, then by the sum of where each is found (title
* over heading over text), then by title, capped at
* {@link PACKAGE_DOC_SEARCH_MAX_RESULTS}.
* - **An answer carries the page's console address** where the page has one
* (a page with no package has none), so the client can cite a source the
* user can open.
*/
export function registerPackageDocTools(
server: McpServer,
bridge: Partial<McpDataBridge>,
options: RegisterObjectToolsOptions = {},
): string[] {
if (!packageDocToolsServed(bridge, options)) return [];
const search = bridge.searchPackageDocs!.bind(bridge);
const read = bridge.readPackageDoc!.bind(bridge);

server.registerTool(
SEARCH_PACKAGE_DOCS_TOOL_NAME,
{
description:
'Find pages in the manuals of the apps installed here that contain business words, before you answer what '
+ 'a term means or how a process works. Send each term as the user wrote it, without question words '
+ '("回款", not "什么是回款"). A page matches when its title, a heading or its text contains a term, case '
+ 'aside. Pages that contain more of the terms come first, then pages where the terms sit higher (title, '
+ `then heading, then text), then by title; at most ${PACKAGE_DOC_SEARCH_MAX_RESULTS}, each with an excerpt `
+ 'and, where the page has one, the url to cite. Only pages this connection may read are searched; on an '
+ 'OAuth connection that is judged on the connection\'s grant, not on the person\'s own permission sets. '
+ `Read a page with ${READ_PACKAGE_DOC_TOOL_NAME}.`,
inputSchema: strictToolInput(
{
surface: `this ${SEARCH_PACKAGE_DOCS_TOOL_NAME} call`,
aliases: { query: 'terms', q: 'terms', keywords: 'terms', term: 'terms', packageId: 'package', app: 'package' },
},
{
terms: z.array(z.string().trim().min(1)).min(1).max(5)
.describe('One to five business words or short phrases, as the user wrote them'),
package: z.string().optional().describe('Only this app\'s manuals'),
},
),
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
},
async ({ terms, package: pkg }) => {
try {
return textResult(await search(
{ terms, ...(pkg !== undefined ? { package: pkg } : {}) },
{ maxResults: PACKAGE_DOC_SEARCH_MAX_RESULTS },
));
} catch (err) {
return errorResultWithCode(err);
}
},
);

server.registerTool(
READ_PACKAGE_DOC_TOOL_NAME,
{
description:
'Read one page of an installed app\'s manual by its name (the name search_package_docs answers): its '
+ 'title, its manual, its Markdown content and, where the page has one, its url to cite. Send package when '
+ 'two apps ship a page of that name. A page this connection may not read answers as not found; on an OAuth '
+ 'connection that is judged on the connection\'s grant, not on the person\'s own permission sets.',
inputSchema: strictToolInput(
{
surface: `this ${READ_PACKAGE_DOC_TOOL_NAME} call`,
aliases: { doc: 'name', docName: 'name', doc_name: 'name', packageId: 'package', app: 'package' },
},
{
name: z.string().trim().min(1).describe('The page\'s name'),
package: z.string().optional().describe('The app that ships the page, when two apps ship that name'),
locale: z.string().optional().describe('A translation of the page to read, e.g. zh-CN; the base text when it has none'),
},
),
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
},
async ({ name, package: pkg, locale }) => {
try {
const page = await read({
name,
...(pkg !== undefined ? { package: pkg } : {}),
...(locale !== undefined ? { locale } : {}),
});
if (typeof page?.content === 'string' && page.content.length > READ_PACKAGE_DOC_MAX_CHARS) {
return textResult({
...page,
content: page.content.slice(0, READ_PACKAGE_DOC_MAX_CHARS),
truncated: `The page is ${page.content.length} characters; this answer carries the first ${READ_PACKAGE_DOC_MAX_CHARS}. Open its url for the rest.`,
});
}
return textResult(page);
} catch (err) {
return errorResultWithCode(err);
}
},
);

return [SEARCH_PACKAGE_DOCS_TOOL_NAME, READ_PACKAGE_DOC_TOOL_NAME];
}

/**
* [#27745] Register the federation pair, `list_remote_tables` and
* `import_object`, over {@link McpFederationBridge}.
Expand Down
Loading
Loading