Skip to content
Draft
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
30 changes: 30 additions & 0 deletions .changeset/37141-skill-context-key.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
---
'@objectstack/spec': minor
'@objectstack/mcp': minor
'@objectstack/lint': minor
'@objectstack/runtime': minor
'@objectstack/platform-objects': minor
---

feat(ai): a skill names the context pack it works from (`context`), and its MCP prompt takes a record id

Clause-②: yes (widening)
Metadata-protocol: added

ADR-0160 D8. A skill can now name a context pack (`ai_context`) by its bare name:

```ts
defineSkill({
name: 'policy_inquiry',
label: 'Policy inquiry',
instructions: 'Answer the question about this policy, citing its sections.',
tools: ['get_record_context'],
context: 'policy_document',
});
```

- **`@objectstack/spec`.** `SkillSchema.context?: string` (snake_case, the pack's machine name; a face such as `NS-NAME` is refused). A skill that declares it must bind `get_record_context` in `tools`, by name or by a wildcard that matches it (`get_record*`, `get_*`); without the binding it is refused at parse, located on `tools`. `skillBindsRecordContextTool(tools)` answers that binding. The skill form gains a `context` control.
- **`@objectstack/mcp`.** When a skill's `context` resolves to a pack, its prompt lists one optional argument, `recordId`. The name resolves by ADR-0150 D3 from the skill's own package (its own pack, else the one holder in its dependency closure), or as for a caller with no package for an environment skill; a name that resolves to no pack adds no argument. Given a record id, the prompt's one message is the skill's instructions, one fixed line telling the model to call `get_record_context` with the arguments that follow, and those arguments as one JSON object: `objectName` (the pack's root), `recordId`, and `context` (the pack's face). The record id only ever appears as that JSON string value, and the pack is never inlined. Without the argument the prompt is byte-identical to the same skill's prompt without `context`. A blank record id is refused (`-32602`). Both the per-request HTTP prompt surface and the long-lived stdio server serve it. `McpSkillBridge` gains two optional members, `listContextPacks` and `packageResolutionClosure`; `MCPServerRuntime.bridgePrompts` takes the closure as an optional fourth argument.
- **`@objectstack/lint`.** Two warnings where skills are validated (`os validate`): `ai-skill-context-unknown`, for a `context` that names no pack the stack defines, and `ai-skill-context-omitted`, for a skill that binds `get_record_context` without `context` while an object has more than one pack (its call there without a pack name is refused).
- **`@objectstack/runtime`.** The `/mcp` route's bridge hands the skill prompt surface the same pack listing `get_record_context` selects from, and the skill's package closure.
- **`@objectstack/platform-objects`.** The generated metadata-form translation bundles carry the skill form's new `context` control (label and help text, translated in every shipped locale).
1 change: 1 addition & 0 deletions content/docs/references/ai/skill.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const result = SkillSchema.parse(data);
| **triggerConditions** | `{ field: string; operator: Enum<'eq' \| 'neq' \| 'in' \| 'not_in' \| 'contains'>; value: string \| string[] }[]` | optional | Programmatic activation conditions — evaluated by the cloud agent runtime only. The context fields a condition reads are reported by the client: a condition is routing, never access control |
| **active** | `boolean` | optional (default: `true`) | Whether the skill is enabled |
| **mcpPrompt** | `boolean` | optional | Whether this skill is offered as an MCP prompt. false = written for the in-product agents only: never listed by prompts/list and unknown to prompts/get on any MCP connection, whatever its tools binding. Absent or true = offered where the server serves its tools |
| **context** | `string` | optional | The context pack (ai_context, by its bare name) this skill works from. Requires get_record_context in tools. Over MCP the skill's prompt then takes an optional record id and asks the model to read that record through the pack |
| **protection** | `{ lock: Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>; reason: string; docsUrl?: string }` | optional | Package author protection block — lock policy for this skill. |
| **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). |
| **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. |
Expand Down
2 changes: 2 additions & 0 deletions packages/lint/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1055,6 +1055,8 @@ export type {
export {
validateAiToolReferences,
AI_SKILL_TOOL_UNRESOLVED,
AI_SKILL_CONTEXT_UNKNOWN,
AI_SKILL_CONTEXT_OMITTED,
} from './validate-ai-tool-references.js';
export type {
AiToolRefFinding,
Expand Down
63 changes: 63 additions & 0 deletions packages/lint/src/validate-ai-tool-references.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import { describe, it, expect } from 'vitest';
import {
validateAiToolReferences as validateAiToolReferencesUnrecorded,
AI_SKILL_CONTEXT_OMITTED,
AI_SKILL_CONTEXT_UNKNOWN,
AI_SKILL_TOOL_UNRESOLVED,
} from './validate-ai-tool-references.js';
import {
Expand Down Expand Up @@ -615,3 +617,64 @@ describe('[#22161] one-line fixes — ai-skill-tool-unresolved', () => {
expect(text).toContain(`(${askOnly.sort().map((n) => `\`${n}\``).join(', ')})`);
});
});

describe('[ADR-0160 D8] a skill\'s context pack reference', () => {
const policyPack = { name: 'policy_document', label: 'Policy document', object: 'policy' };
const reviewPack = { name: 'policy_review', label: 'Policy review', object: 'policy' };
const casePack = { name: 'case_brief', label: 'Case brief', object: 'case' };
const skill = (extra: Record<string, unknown>) => ({
name: 'policy_inquiry',
label: 'Policy inquiry',
instructions: 'Answer questions about one policy.',
tools: ['get_record_context'],
...extra,
});
const contextFindings = (stack: Record<string, unknown>) =>
validateAiToolReferences(stack).filter((f) => f.rule !== AI_SKILL_TOOL_UNRESOLVED);

it('reports a context that names no pack the stack defines, located on the key', () => {
const findings = contextFindings({ aiContexts: [policyPack], skills: [skill({ context: 'policy_documnt' })] });
expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([[AI_SKILL_CONTEXT_UNKNOWN, 'warning', 'skills[0].context']]);
expect(findings[0].message).toContain('"policy_documnt"');
expect(findings[0].message).toContain('Did you mean "policy_document"?');
});

it('CONTROL — a context that names a pack the stack defines is clean, even beside a second pack on its object', () => {
expect(contextFindings({ aiContexts: [policyPack, reviewPack], skills: [skill({ context: 'policy_document' })] })).toEqual([]);
});

it('a stack with no packs reports the reference as unknown', () => {
expect(contextFindings({ skills: [skill({ context: 'policy_document' })] }).map((f) => f.rule)).toEqual([AI_SKILL_CONTEXT_UNKNOWN]);
});

it('advises a skill that binds get_record_context without context when an object has several packs (ADR-0160 D1, point 1)', () => {
const findings = contextFindings({ aiContexts: [policyPack, casePack, reviewPack], skills: [skill({})] });
expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([[AI_SKILL_CONTEXT_OMITTED, 'warning', 'skills[0]']]);
expect(findings[0].message).toContain("object 'policy' has 2 packs (policy_document, policy_review)");
expect(findings[0].message).not.toContain('case');
});

it('a wildcard that matches get_record_context is a binding for the advisory too', () => {
const findings = contextFindings({ aiContexts: [policyPack, reviewPack], skills: [skill({ tools: ['get_*'] })] });
expect(findings.map((f) => f.rule)).toEqual([AI_SKILL_CONTEXT_OMITTED]);
});

it('CONTROL — no advisory when every object has one pack, or when the skill does not bind the tool', () => {
expect(contextFindings({ aiContexts: [policyPack, casePack], skills: [skill({})] })).toEqual([]);
expect(contextFindings({ aiContexts: [policyPack, reviewPack], skills: [skill({ tools: ['get_record'] })] })).toEqual([]);
});

it('each verdict and fix is one line of at most 200 characters', () => {
const findings = contextFindings({
aiContexts: [policyPack, reviewPack],
skills: [skill({ context: 'policy_documnt' }), skill({ name: 'other' })],
});
expect(findings.map((f) => f.rule).sort()).toEqual([AI_SKILL_CONTEXT_OMITTED, AI_SKILL_CONTEXT_UNKNOWN]);
for (const f of findings) {
for (const line of [f.message, f.hint]) {
expect(line).not.toContain('\n');
expect(line.length, line).toBeLessThanOrEqual(200);
}
}
});
});
83 changes: 82 additions & 1 deletion packages/lint/src/validate-ai-tool-references.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
* positives (6 references resolve via the registry).
*/

import { GET_RECORD_CONTEXT_TOOL_NAME, skillBindsRecordContextTool } from '@objectstack/spec/ai';
import {
MCP_DOOR_TOOL_NAMES,
PLATFORM_PROVIDED_TOOL_NAMES,
Expand All @@ -60,6 +61,10 @@ import {
import { recordsOf, suggestName } from './object-graph.js';

export const AI_SKILL_TOOL_UNRESOLVED = 'ai-skill-tool-unresolved';
/** [ADR-0160 D8] A skill's `context` names no context pack. */
export const AI_SKILL_CONTEXT_UNKNOWN = 'ai-skill-context-unknown';
/** [ADR-0160 D1 advisory, point 1] A skill reads packs without naming one, on an object with several. */
export const AI_SKILL_CONTEXT_OMITTED = 'ai-skill-context-omitted';

export type AiToolRefSeverity = 'error' | 'warning';

Expand Down Expand Up @@ -242,7 +247,82 @@ function projectedOverMcp(skill: AnyRec): boolean {
}

/**
* Validate every `skill.tools[]` reference in a stack. Returns findings
* [ADR-0160 D8; D1 "Advisory reports", point 1's third condition] A skill's
* context-pack reference, judged against the stack's own packs
* (`stack.aiContexts`). Two verdicts, each a `warning`:
*
* - {@link AI_SKILL_CONTEXT_UNKNOWN}: `context` names no pack the stack
* defines. At run time the prompt lists no record argument and the tool call
* it would lead to is refused; no other pack is substituted (D8).
* - {@link AI_SKILL_CONTEXT_OMITTED}: the skill binds `get_record_context`
* (by name or a matching wildcard) and declares no `context`, and some object
* has more than one pack. The call it makes without `context` on such an
* object is refused, listing the candidates (D4); the configuration is
* legal, so this is advisory.
*
* A stack is one holder here: the pack names it declares are the ones its own
* skills resolve to first (ADR-0150 D3 step 1). A pack only a dependency
* package ships is not in this stack, and is reported as unknown.
*/
export function validateAiSkillContext(stack: AnyRec): AiToolRefFinding[] {
const findings: AiToolRefFinding[] = [];
if (!stack || typeof stack !== 'object') return findings;

const packNames = new Set<string>();
const packsByObject = new Map<string, string[]>();
for (const pack of recordsOf(stack.aiContexts)) {
const name = strName(pack.name);
if (!name) continue;
packNames.add(name);
const object = strName(pack.object);
if (!object) continue;
const names = packsByObject.get(object) ?? [];
if (!names.includes(name)) names.push(name);
packsByObject.set(object, names);
}
const severalPacks = [...packsByObject].filter(([, names]) => names.length > 1);

const skills = recordsOf(stack.skills);
for (let si = 0; si < skills.length; si++) {
const skill = skills[si];
const skillName = strName(skill.name) ?? `#${si}`;
const context = strName(skill.context);
if (context !== undefined) {
if (packNames.has(context)) continue;
findings.push({
severity: 'warning',
rule: AI_SKILL_CONTEXT_UNKNOWN,
where: `skill "${skillName}" · context`,
path: `skills[${si}].context`,
message:
`\`context\` names context pack "${context}", which this stack does not define, so the skill's MCP prompt ` +
`takes no record and its ${GET_RECORD_CONTEXT_TOOL_NAME} call is refused.` +
suggestName(context, packNames),
hint: 'Name a pack the stack defines under `aiContexts` (check the spelling), or remove `context`',
});
continue;
}
if (!skillBindsRecordContextTool(skill.tools)) continue;
// One finding per such object: each names its own packs.
for (const [object, names] of severalPacks) {
findings.push({
severity: 'warning',
rule: AI_SKILL_CONTEXT_OMITTED,
where: `skill "${skillName}" · context`,
path: `skills[${si}]`,
message:
`The skill binds ${GET_RECORD_CONTEXT_TOOL_NAME} without \`context\`, and object '${object}' has ` +
`${names.length} packs (${names.join(', ')}), so its call there without a pack name is refused`,
hint: 'Set `context` to the pack this skill works from',
});
}
}
return findings;
}

/**
* Validate every `skill.tools[]` reference in a stack, and each skill's
* context-pack reference ({@link validateAiSkillContext}). Returns findings
* (empty = clean).
*/
export function validateAiToolReferences(stack: AnyRec): AiToolRefFinding[] {
Expand Down Expand Up @@ -346,5 +426,6 @@ export function validateAiToolReferences(stack: AnyRec): AiToolRefFinding[] {
}
}

findings.push(...validateAiSkillContext(stack));
return findings;
}
100 changes: 65 additions & 35 deletions packages/mcp/src/mcp-server-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,11 @@ import {
registerSkillPrompts,
skillPromptFaces,
skillPromptListEntry,
skillPromptRecordArgument,
skillPromptRefusalError,
skillPromptResult,
skillPromptWithdrawn,
SKILL_PROMPT_RECORD_ARGUMENT,
type McpSkillBridge,
type SkillPrompt,
} from './skill-prompts.js';
Expand Down Expand Up @@ -1204,11 +1206,13 @@ function routeBareSkillPromptNames(
const sdkGet = map.get('prompts/get');
if (!sdkGet) return;
map.set('prompts/get', async (request, extra) => {
const wanted = (request as { params?: { name?: unknown } } | null | undefined)?.params?.name;
const params = (request as { params?: { name?: unknown; arguments?: Record<string, unknown> } } | null | undefined)?.params;
const wanted = params?.name;
if (typeof wanted === 'string' && !registered.has(wanted)) {
const lookup = lookupSkillPrompt(await listSkills(), wanted);
if (lookup.status === 'refused') throw skillPromptRefusalError(lookup);
if (lookup.status === 'found') return skillPromptResult(lookup.prompt);
// [ADR-0160 D8] The record argument, as on the face's own get.
if (lookup.status === 'found') return skillPromptResult(lookup.prompt, params?.arguments);
}
return sdkGet(request, extra);
});
Expand Down Expand Up @@ -2559,6 +2563,13 @@ export class MCPServerRuntime {
* from (`NS-NAME`). Omitted, every face is the item's bare name.
*/
packageNamespace?: (packageId: string) => string | undefined,
/**
* [ADR-0150 D3 step 2, ADR-0160 D8] A package's resolution closure, which a
* package-held skill's `context` resolves through
* (`McpSkillBridge.packageResolutionClosure`). Omitted, such a skill
* resolves only its own package's pack.
*/
packageResolutionClosure?: (packageId: string) => ReadonlySet<string>,
): Promise<void> {
const logger = this.config.logger;

Expand Down Expand Up @@ -2654,6 +2665,11 @@ export class MCPServerRuntime {
let skillListVerdict: { degraded: boolean; errors: string[] } = { degraded: false, errors: [] };
const skillBridge: McpSkillBridge = {
...(packageNamespace ? { packageNamespace } : {}),
...(packageResolutionClosure ? { packageResolutionClosure } : {}),
// [ADR-0160 D8] The packs a skill's `context` resolves against: the
// merged listing, the one the stdio bridge's `get_record_context` reads
// its packs from, so the face a prompt hands on is one the tool selects.
listContextPacks: async () => (await mergedDiagnosedList(metadataService, mergedRead, 'ai_context')).items,
listSkills: async () => {
// The verdict of the READ, recorded as the read happens. `listSkills`
// is also the per-call re-read behind each registered prompt's body, so
Expand Down Expand Up @@ -2715,40 +2731,54 @@ export class MCPServerRuntime {
}
if (entry.prompts.length > 1) logger?.warn(`[MCP] ${duplicateSkillFaceMessage(entry)}`);
const listed = skillPromptListEntry(entry);
this.mcpServer.registerPrompt(
entry.face,
{
...(listed.title ? { title: listed.title } : {}),
...(listed.description ? { description: listed.description } : {}),
},
async () => {
// Re-read at call time so an edited skill serves fresh instructions.
// One read: the projection and the withdrawal check below see the same rows.
const rows = (await skillBridge.listSkills()) ?? [];
const lookup = lookupSkillPrompt(
await listSkillPrompts({ ...skillBridge, listSkills: async () => rows }),
entry.face,
);
if (lookup.status === 'refused') throw skillPromptRefusalError(lookup);
if (lookup.status === 'found') return skillPromptResult(lookup.prompt);
if (entry.prompts.length === 1) {
// [#34167] Withdrawn since the snapshot (`mcpPrompt: false`):
// answered as the SDK answers a name it never registered. This
// server's list is a boot snapshot and keeps the name until
// restart; the get stops serving it at once.
if (skillPromptWithdrawn(rows, entry.prompts[0])) {
throw new McpError(ErrorCode.InvalidParams, `Prompt ${entry.face} not found`);
}
// Gone since the snapshot: the snapshot's one skill, as before.
return skillPromptResult(entry.prompts[0]);
// [ADR-0160 D8] A skill whose `context` resolved to a pack at this
// snapshot lists the record argument; the SDK hands a get its value.
const recordArgument = listed.arguments ? skillPromptRecordArgument() : undefined;
const serve = async (args?: Record<string, unknown>) => {
// Re-read at call time so an edited skill serves fresh instructions.
// One read: the projection and the withdrawal check below see the same rows.
const rows = (await skillBridge.listSkills()) ?? [];
const lookup = lookupSkillPrompt(
await listSkillPrompts({ ...skillBridge, listSkills: async () => rows }),
entry.face,
);
if (lookup.status === 'refused') throw skillPromptRefusalError(lookup);
if (lookup.status === 'found') return skillPromptResult(lookup.prompt, args);
if (entry.prompts.length === 1) {
// [#34167] Withdrawn since the snapshot (`mcpPrompt: false`):
// answered as the SDK answers a name it never registered. This
// server's list is a boot snapshot and keeps the name until
// restart; the get stops serving it at once.
if (skillPromptWithdrawn(rows, entry.prompts[0])) {
throw new McpError(ErrorCode.InvalidParams, `Prompt ${entry.face} not found`);
}
throw skillPromptRefusalError({
status: 'refused',
message: duplicateSkillFaceMessage(entry),
candidates: entry.prompts.map((p) => p.face),
});
},
);
// Gone since the snapshot: the snapshot's one skill, as before.
return skillPromptResult(entry.prompts[0], args);
}
throw skillPromptRefusalError({
status: 'refused',
message: duplicateSkillFaceMessage(entry),
candidates: entry.prompts.map((p) => p.face),
});
};
const config = {
...(listed.title ? { title: listed.title } : {}),
...(listed.description ? { description: listed.description } : {}),
};
if (recordArgument) {
this.mcpServer.registerPrompt(
entry.face,
{
...config,
argsSchema: {
[SKILL_PROMPT_RECORD_ARGUMENT]: z.string().optional().describe(recordArgument.description),
},
},
async (args) => serve(args),
);
} else {
this.mcpServer.registerPrompt(entry.face, config, async () => serve());
}
registeredNames.add(entry.face);
bridged++;
}
Expand Down
Loading
Loading