The open-source agent harness - the runtime layer that turns an LLM into a working agent.
feat: resolve MCP servers and skills from x-tfg-mcp and x-tfg-skills (#592)
pranjaltrvd12978acc90eb
diff --git a/.changeset/20260904140000-inline-mcp-and-skills.md b/.changeset/20260904140000-inline-mcp-and-skills.mdnew file mode 100644index 000000000..6855e6324--- /dev/null+++ b/.changeset/20260904140000-inline-mcp-and-skills.md@@ -0,0 +1,5 @@+---+"@truefoundry/trueforge": patch+---++Accept `x-tfg-mcp` and `x-tfg-skills` in TrueFoundry mode: MCP servers and skills a request defines by name, taking precedence over the tenant registry for that request only. Both resolve for spec validation and turn execution; an unfiltered list still shows only configured resources, so request-scoped ones never appear in settings. Inline MCP credentials come from the manifest's own `auth.headers`, which lets a rotating token ride each turn.diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.tsindex f2dc59083..944500498 100644--- a/packages/trueforge/src/main.ts+++ b/packages/trueforge/src/main.ts@@ -87,6 +87,9 @@ import { PACKAGE_VERSION } from './packageVersion';import { ActiveTurnRegistry } from './runtime/activeTurns';import { EventSubscriptionRegistry } from './runtime/event-subscription';import { printStandaloneStartupBanner } from './startupBanner';+import { InlineMcpServerStore } from './truefoundry/InlineMcpServerStore';+import { parseInlineMcpServers, parseInlineSkills, X_TFG_MCP, X_TFG_SKILLS } from './truefoundry/inlineResources';+import { InlineSkillStore } from './truefoundry/InlineSkillStore';import {parsePerServerMcpHeaders,X_TFG_MCP_HEADERS,@@ -542,15 +545,33 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<return mcpOAuthStore;}const rawPerServerHeaders = c.req.header(X_TFG_MCP_HEADERS);- return persistence.resolveMcpServerStore(+ const store = persistence.resolveMcpServerStore(resolveRequestContext(c),runAsAgent,rawPerServerHeaders === undefined ? undefined : parsePerServerMcpHeaders(rawPerServerHeaders),);+ if (!isTrueFoundryModeEnabled(configuration)) {+ return store;+ }+ const rawInline = c.req.header(X_TFG_MCP);+ if (rawInline === undefined) {+ return store;+ }+ return new InlineMcpServerStore({ inner: store, inline: parseInlineMcpServers(rawInline) });};const resolveAgentStore = (c: Context) => persistence.resolveAgentStore(resolveRequestContext(c));const resolveSandboxProviderStore = (c: Context) => persistence.resolveSandboxProviderStore(resolveRequestContext(c));- const resolveSkillStore = (c: Context) => persistence.resolveSkillStore(resolveRequestContext(c));+ const resolveSkillStore = (c: Context) => {+ const store = persistence.resolveSkillStore(resolveRequestContext(c));+ if (!isTrueFoundryModeEnabled(configuration)) {+ return store;+ }+ const rawInline = c.req.header(X_TFG_SKILLS);+ if (rawInline === undefined) {+ return store;+ }+ return new InlineSkillStore({ inner: store, inline: parseInlineSkills(rawInline) });+ };const app = createServerApp({modelCatalog: ModelCatalog.load(),mcpCatalog: McpCatalog.load(),diff --git a/packages/trueforge/src/truefoundry/InlineMcpServerStore.ts b/packages/trueforge/src/truefoundry/InlineMcpServerStore.tsnew file mode 100644index 000000000..3d7b4135f--- /dev/null+++ b/packages/trueforge/src/truefoundry/InlineMcpServerStore.ts@@ -0,0 +1,130 @@+import type { RemoteMcpHeaders } from '@truefoundry/trueforge-core/core';+import type {+ AuthorizeMcpServerInput,+ CreateMcpServerInput,+ DeleteMcpAuthorizationInput,+ GetMcpServerInput,+ IMcpServerWithAuthStore,+ ListMcpServersInput,+ McpServerRecord,+ ResolveMcpAuthStatusesInput,+ UpsertMcpServerInput,+} from '../db/mcpServerStore';+import type { OAuthClientRecord } from '../mcp/auth/types';+import { resolveConfiguredMcpRequestHeaders, resolveMcpAuthStatus, type McpAuthStatus } from '../schemas/mcpServer';+import type { InlineMcpServers } from './inlineResources';++/**+ * Serves the MCP servers a request brought with it, and delegates everything else.+ *+ * Only the resolve paths are overlaid — by-name lookup, name-filtered list, invoke headers and+ * auth status. An unfiltered list passes straight through, so a request-scoped server never shows+ * up in the tenant's settings. Writes and OAuth delegate too: there is no row to write or+ * authorize against.+ */+export class InlineMcpServerStore<TTransaction = never> implements IMcpServerWithAuthStore<TTransaction> {+ readonly #inner: IMcpServerWithAuthStore<TTransaction>;+ readonly #inline: InlineMcpServers;++ constructor(input: { inner: IMcpServerWithAuthStore<TTransaction>; inline: InlineMcpServers }) {+ this.#inner = input.inner;+ this.#inline = input.inline;+ }++ /**+ * The manifest carries its own credentials, so they go to the upstream as written — no caller+ * bearer is added and nothing is stripped. That is what lets a token rotate per request.+ */+ resolveInvokeHeaders(input: { record: McpServerRecord; userRef: string }): RemoteMcpHeaders {+ const manifest = this.#inline[input.record.name];+ if (manifest === undefined) {+ return this.#inner.resolveInvokeHeaders(input);+ }+ return resolveConfiguredMcpRequestHeaders(manifest);+ }++ async getServer(input: GetMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord | undefined> {+ const record = this.#toRecord({ tenant_id: input.tenant_id, name: input.name });+ return record ?? (await this.#inner.getServer(input, transaction));+ }++ async listServers(input: ListMcpServersInput, transaction?: TTransaction): Promise<McpServerRecord[]> {+ if (input.names === undefined) {+ return this.#inner.listServers(input, transaction);+ }+ if (input.names.length === 0) {+ return [];+ }++ const inlineRecords = input.names+ .map(name => this.#toRecord({ tenant_id: input.tenant_id, name }))+ .filter((record): record is McpServerRecord => record !== undefined);+ const registryNames = input.names.filter(name => this.#inline[name] === undefined);+ const registryRecords =+ registryNames.length > 0 ? await this.#inner.listServers({ ...input, names: registryNames }, transaction) : [];++ return [...inlineRecords, ...registryRecords];+ }++ async resolveAuthStatuses(input: ResolveMcpAuthStatusesInput): Promise<ReadonlyMap<string, McpAuthStatus>> {+ const inlineRecords = input.records.filter(record => this.#inline[record.name] !== undefined);+ const registryRecords = input.records.filter(record => this.#inline[record.name] === undefined);++ const statuses = new Map<string, McpAuthStatus>(+ registryRecords.length > 0 ? await this.#inner.resolveAuthStatuses({ ...input, records: registryRecords }) : [],+ );+ for (const record of inlineRecords) {+ statuses.set(record.name, resolveMcpAuthStatus({ manifest: record.manifest }));+ }+ return statuses;+ }++ getServerForUpdate(input: GetMcpServerInput, transaction: TTransaction): Promise<McpServerRecord | undefined> {+ return this.#inner.getServerForUpdate(input, transaction);+ }++ createServer(input: CreateMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord> {+ return this.#inner.createServer(input, transaction);+ }++ upsertServer(input: UpsertMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord> {+ return this.#inner.upsertServer(input, transaction);+ }++ authorize(input: AuthorizeMcpServerInput): Promise<McpAuthStatus> {+ return this.#inner.authorize(input);+ }++ deleteAuthorization(input: DeleteMcpAuthorizationInput): Promise<void> {+ return this.#inner.deleteAuthorization(input);+ }++ saveClient(params: { id: string; record: OAuthClientRecord }, transaction?: TTransaction): Promise<void> {+ return this.#inner.saveClient(params, transaction);+ }++ getClient(params: { id: string }, transaction?: TTransaction): Promise<OAuthClientRecord | undefined> {+ return this.#inner.getClient(params, transaction);+ }++ deleteClient(params: { id: string }, transaction?: TTransaction): Promise<void> {+ return this.#inner.deleteClient(params, transaction);+ }++ /** `id` is the name: nothing is persisted, and the name is what identifies these downstream. */+ #toRecord(input: { tenant_id: string; name: string }): McpServerRecord | undefined {+ const manifest = this.#inline[input.name];+ if (manifest === undefined) {+ return undefined;+ }+ const now = new Date().toISOString();+ return {+ id: input.name,+ tenant_id: input.tenant_id,+ name: manifest.name,+ manifest,+ created_at: now,+ updated_at: now,+ };+ }+}diff --git a/packages/trueforge/src/truefoundry/InlineSkillStore.ts b/packages/trueforge/src/truefoundry/InlineSkillStore.tsnew file mode 100644index 000000000..69a468eed--- /dev/null+++ b/packages/trueforge/src/truefoundry/InlineSkillStore.ts@@ -0,0 +1,123 @@+import type { Skill as SkillMount } from '@truefoundry/trueforge-core/core';+import { HTTPException } from 'hono/http-exception';+import { resolveGitTurnSkills, validateGitAgentSkills } from '../db/gitSkillMounts';+import type {+ AgentSkillsInput,+ CreateSkillInput,+ ISkillStore,+ ListSkillsInput,+ SkillRecord,+ UpsertSkillInput,+} from '../db/skillStore';+import type { SkillVersion } from '../schemas/skill';+import type { InlineSkills } from './inlineResources';++/**+ * Serves the skills a request brought with it, and delegates everything else.+ *+ * Mirrors {@link InlineMcpServerStore}: name-filtered list and validate/resolve are overlaid, an+ * unfiltered list passes through so request-scoped skills stay out of the tenant's settings, and+ * writes delegate because there is no row to write.+ */+export class InlineSkillStore<TTransaction = never> implements ISkillStore<TTransaction> {+ readonly #inner: ISkillStore<TTransaction>;+ readonly #inline: InlineSkills;++ constructor(input: { inner: ISkillStore<TTransaction>; inline: InlineSkills }) {+ this.#inner = input.inner;+ this.#inline = input.inline;+ }++ async listSkills(input: ListSkillsInput, transaction?: TTransaction): Promise<SkillRecord[]> {+ if (input.names === undefined) {+ return this.#inner.listSkills(input, transaction);+ }+ if (input.names.length === 0) {+ return [];+ }++ const inlineRecords = input.names+ .map(name => this.#toRecord({ tenant_id: input.tenant_id, name }))+ .filter((record): record is SkillRecord => record !== undefined);+ const registryNames = input.names.filter(name => this.#inline[name] === undefined);+ const registryRecords =+ registryNames.length > 0 ? await this.#inner.listSkills({ ...input, names: registryNames }, transaction) : [];++ return [...inlineRecords, ...registryRecords];+ }++ createSkill(input: CreateSkillInput, transaction?: TTransaction): Promise<SkillRecord> {+ return this.#inner.createSkill(input, transaction);+ }++ upsertSkill(input: UpsertSkillInput, transaction?: TTransaction): Promise<SkillRecord> {+ return this.#inner.upsertSkill(input, transaction);+ }++ listSkillVersions(input: { name: string }): Promise<SkillVersion[]> {+ if (this.#inline[input.name] !== undefined) {+ return Promise.resolve([]);+ }+ return this.#inner.listSkillVersions(input);+ }++ async validateAgentSkills(input: AgentSkillsInput, transaction?: TTransaction): Promise<void> {+ const { inlineSkills, registrySkills } = this.#partition(input.skills);+ if (inlineSkills.length > 0) {+ await validateGitAgentSkills(this, { tenant_id: input.tenant_id, skills: inlineSkills });+ }+ // Cross-source uniqueness needs registry short names from resolveTurnSkills; keep that out of+ // validate so mixed specs are not failed for API-key / presigned-URL requirements.+ if (registrySkills.length > 0) {+ await this.#inner.validateAgentSkills({ tenant_id: input.tenant_id, skills: registrySkills }, transaction);+ }+ }++ async resolveTurnSkills(input: AgentSkillsInput): Promise<SkillMount[]> {+ const { inlineSkills, registrySkills } = this.#partition(input.skills);+ const inlineMounts =+ inlineSkills.length > 0+ ? await resolveGitTurnSkills(this, { tenant_id: input.tenant_id, skills: inlineSkills })+ : [];+ const registryMounts =+ registrySkills.length > 0+ ? await this.#inner.resolveTurnSkills({ tenant_id: input.tenant_id, skills: registrySkills })+ : [];+ const mounts = [...inlineMounts, ...registryMounts];+ // Inline key and registry short name share the sandbox dir — reject collisions here.+ const seen = new Set<string>();+ for (const mount of mounts) {+ if (seen.has(mount.name)) {+ throw new HTTPException(422, {+ message: `Agent skills must have unique names; duplicate skill name(s): ${mount.name}`,+ });+ }+ seen.add(mount.name);+ }+ return mounts;+ }++ #partition(skills: AgentSkillsInput['skills']): {+ inlineSkills: AgentSkillsInput['skills'];+ registrySkills: AgentSkillsInput['skills'];+ } {+ const inlineSkills = skills.filter(skill => this.#inline[skill.name] !== undefined);+ const registrySkills = skills.filter(skill => this.#inline[skill.name] === undefined);+ return { inlineSkills, registrySkills };+ }++ #toRecord(input: { tenant_id: string; name: string }): SkillRecord | undefined {+ const manifest = this.#inline[input.name];+ if (manifest === undefined) {+ return undefined;+ }+ const now = new Date().toISOString();+ return {+ tenant_id: input.tenant_id,+ name: manifest.name,+ manifest,+ created_at: now,+ updated_at: now,+ };+ }+}diff --git a/packages/trueforge/src/truefoundry/inlineResources.ts b/packages/trueforge/src/truefoundry/inlineResources.tsnew file mode 100644index 000000000..681899b42--- /dev/null+++ b/packages/trueforge/src/truefoundry/inlineResources.ts@@ -0,0 +1,92 @@+/**+ * MCP servers and skills supplied per request instead of configured in the tenant's registry,+ * each keyed by name.+ *+ * A caller that owns its own agent definition brings resources the tenant never registered and+ * should not see in its settings or its gateway metrics. Sending them per request keeps them out+ * of the registry entirely, and lets a rotating credential ride each turn rather than being+ * stored somewhere it will go stale.+ */+import { HTTPException } from 'hono/http-exception';+import { McpServerManifestSchema, type McpServerManifest } from '../schemas/mcpServer';+import { SkillManifestSchema, type SkillManifest } from '../schemas/skill';++export const X_TFG_MCP = 'x-tfg-mcp';+export const X_TFG_SKILLS = 'x-tfg-skills';++/** Manifests by name. `type` and `name` are implied by the header and the key, so callers omit them. */+export type InlineMcpServers = Readonly<Record<string, McpServerManifest>>;+export type InlineSkills = Readonly<Record<string, SkillManifest>>;++export function parseInlineMcpServers(raw: string): InlineMcpServers {+ return parseByName({+ raw,+ header: X_TFG_MCP,+ parseEntry: (name, definition) => {+ const parsed = McpServerManifestSchema.safeParse({ ...definition, type: 'remote', name });+ if (!parsed.success) {+ return { ok: false, reason: 'is not a valid MCP server definition' };+ }+ if (parsed.data.auth?.type === 'dcr') {+ return { ok: false, reason: 'cannot use dcr auth — it needs a registered client and a stored token' };+ }+ return { ok: true, manifest: parsed.data };+ },+ });+}++export function parseInlineSkills(raw: string): InlineSkills {+ return parseByName({+ raw,+ header: X_TFG_SKILLS,+ parseEntry: (name, definition) => {+ const parsed = SkillManifestSchema.safeParse({ ...definition, type: 'git', name });+ return parsed.success+ ? { ok: true, manifest: parsed.data }+ : { ok: false, reason: 'is not a valid skill definition' };+ },+ });+}++type EntryResult<TManifest> = { ok: true; manifest: TManifest } | { ok: false; reason: string };++/**+ * Rejects a malformed value rather than dropping it. Falling back to the tenant registry, where+ * these resources do not exist, would surface as a confusing "not configured" much later on.+ */+function parseByName<TManifest>(input: {+ raw: string;+ header: string;+ parseEntry: (name: string, definition: object) => EntryResult<TManifest>;+}): Readonly<Record<string, TManifest>> {+ const { raw, header, parseEntry } = input;+ let decoded: unknown;+ try {+ decoded = JSON.parse(raw);+ } catch (error) {+ throw new HTTPException(400, { message: `${header} must be a JSON object`, cause: error });+ }+ if (!isPlainObject(decoded)) {+ throw new HTTPException(400, { message: `${header} must map each name to a definition` });+ }++ // `{}` inherits Object.prototype, so `map['constructor']` is Object (not undefined).+ // NameSchema allows `constructor`, so strip the prototype (avoids Object.create(null)'s `any`).+ const manifests: Record<string, TManifest> = {};+ Object.setPrototypeOf(manifests, null);+ for (const [name, definition] of Object.entries(decoded)) {+ if (!isPlainObject(definition)) {+ throw new HTTPException(400, { message: `${header} entry "${name}" must be an object` });+ }+ const parsed = parseEntry(name, definition);+ if (!parsed.ok) {+ throw new HTTPException(400, { message: `${header} entry "${name}" ${parsed.reason}` });+ }+ manifests[name] = parsed.manifest;+ }+ return manifests;+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}diff --git a/packages/trueforge/tests/unit/truefoundry/askTfyContract.test.ts b/packages/trueforge/tests/unit/truefoundry/askTfyContract.test.tsnew file mode 100644index 000000000..1f177b127--- /dev/null+++ b/packages/trueforge/tests/unit/truefoundry/askTfyContract.test.ts@@ -0,0 +1,107 @@+/**+ * The Ask TFY wire contract, checked against what sfy-server actually sends.+ *+ * sfy-server builds the spec and the two headers in its own repo, so nothing here imports that+ * code. These fixtures mirror its output byte for byte; if it changes shape, this fails rather than+ * the install discovering it on the first turn.+ */+import { AgentSpecSchema } from '@truefoundry/trueforge-core/agent-session';+import { parseInlineMcpServers, parseInlineSkills } from '../../../src/truefoundry/inlineResources';++const MCP_NAMES = ['tfy-platform-mcp', 'tfy-pylon-mcp', 'tfy-docs-mcp', 'tfy-web-search-mcp'] as const;+const SKILL_NAME = 'tfy-platform-skills';++/** Inert filler the length of a TrueFoundry JWT, to size the header realistically. */+const FILLER = 'A'.repeat(1450);++/** The em dash is in the shipped skill description, and a header value cannot carry it raw. */+const SKILL_DESCRIPTION =+ 'Answer questions about TrueFoundry, an enterprise AI platform. Covers two products — AI Gateway ' ++ '(LLM proxy, MCP servers, agents, governance) and AI Engineering.';++/** Mirrors sfy-server's toHeaderJson: JSON with every non-ASCII character escaped. */+function toHeaderJson(value: unknown): string {+ return JSON.stringify(value).replace(+ /[\u007f-\uffff]/g,+ char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`,+ );+}++const spec = {+ model: { name: 'openai/gpt-5' },+ instructions: 'You are Ask TFY.',+ mcp_servers: MCP_NAMES.map(name => ({ name })),+ skills: [{ name: SKILL_NAME }],+ config: { sandbox: { enabled: true } },+};++const mcpHeader = toHeaderJson(+ Object.fromEntries(+ MCP_NAMES.map(name => [+ name,+ {+ url: `https://proxy.truefoundry.com/v1/mcp/${name}/server`,+ description: `Search ${name} — the product’s data.`,+ auth: { type: 'header', headers: { Authorization: `Bearer ${FILLER}` } },+ },+ ]),+ ),+);++const skillsHeader = toHeaderJson({+ [SKILL_NAME]: {+ url: 'https://github.com/truefoundry/tfy-ai-gateway-skills',+ ref: 'a1b2c3d4e5f6',+ path: 'skills',+ description: SKILL_DESCRIPTION,+ },+});++describe('Ask TFY wire contract', () => {+ it('accepts the spec sfy-server sends, filling the defaults it leaves out', () => {+ const parsed = AgentSpecSchema.parse(spec);++ expect(parsed.config.sandbox.enabled).toBe(true);+ expect(parsed.mcp_servers?.map(server => server.name)).toEqual([...MCP_NAMES]);+ expect(parsed.skills).toEqual([{ name: SKILL_NAME, preload: false }]);+ });++ it('resolves every name in the spec from the headers, so none falls through to the registry', () => {+ const servers = parseInlineMcpServers(mcpHeader);+ const skills = parseInlineSkills(skillsHeader);++ for (const name of spec.mcp_servers) {+ expect(servers[name.name]).toBeDefined();+ }+ for (const skill of spec.skills) {+ expect(skills[skill.name]).toBeDefined();+ }+ });++ it('restores the characters a header cannot carry raw', () => {+ const skill = parseInlineSkills(skillsHeader)[SKILL_NAME];+ const docsMcp = parseInlineMcpServers(mcpHeader)['tfy-docs-mcp'];+ expect(skill).toBeDefined();+ expect(docsMcp).toBeDefined();+ expect(skill?.description).toBe(SKILL_DESCRIPTION);+ expect(docsMcp?.description).toContain('—');+ });++ /** Node rejects a header value outside latin-1 outright, so this is a hard requirement. */+ it.each([+ ['x-tfg-mcp', mcpHeader],+ ['x-tfg-skills', skillsHeader],+ ])('sends %s as ASCII only', (_name, value) => {+ expect(value).not.toMatch(/[^\u0000-\u007f]/);+ });++ /**+ * Node's default max header size is 16KB for the whole block, and an ingress in front is often+ * tighter. Four servers each carrying a JWT is the realistic worst case.+ */+ it('keeps the headers within one 8KB ingress buffer', () => {+ const total = Buffer.byteLength(mcpHeader) + Buffer.byteLength(skillsHeader);++ expect(total).toBeLessThan(8 * 1024);+ });+});diff --git a/packages/trueforge/tests/unit/truefoundry/inlineResources.test.ts b/packages/trueforge/tests/unit/truefoundry/inlineResources.test.tsnew file mode 100644index 000000000..8ea0a1e8b--- /dev/null+++ b/packages/trueforge/tests/unit/truefoundry/inlineResources.test.ts@@ -0,0 +1,243 @@+import { HTTPException } from 'hono/http-exception';+import type { IMcpServerWithAuthStore, McpServerRecord } from '../../../src/db/mcpServerStore';+import type { ISkillStore, SkillRecord } from '../../../src/db/skillStore';+import { InlineMcpServerStore } from '../../../src/truefoundry/InlineMcpServerStore';+import { parseInlineMcpServers, parseInlineSkills } from '../../../src/truefoundry/inlineResources';+import { InlineSkillStore } from '../../../src/truefoundry/InlineSkillStore';++const DOCS_MCP = {+ url: 'https://docs.example/mcp',+ description: 'Search the product documentation.',+ auth: { type: 'header', headers: { Authorization: 'Bearer saas-token' } },+};++const ASK_AI_SKILL = {+ url: 'https://github.com/truefoundry/skills',+ ref: 'a1b2c3d',+ path: 'ask-ai',+ description: 'How to answer questions about the platform.',+};++const registryServer: McpServerRecord = {+ id: '01JREGISTRY',+ tenant_id: 'default',+ name: 'team-mcp',+ manifest: { type: 'remote', name: 'team-mcp', url: 'https://team.example/mcp', description: 'Team server.' },+ created_at: '2026-01-15T12:00:00.000Z',+ updated_at: '2026-01-15T12:00:00.000Z',+};++const registrySkill: SkillRecord = {+ tenant_id: 'default',+ name: 'team-skill',+ manifest: {+ type: 'git',+ name: 'team-skill',+ url: 'https://github.com/acme/skills',+ ref: 'main',+ description: 'A skill the tenant configured.',+ },+ created_at: '2026-01-15T12:00:00.000Z',+ updated_at: '2026-01-15T12:00:00.000Z',+};++function mcpStoreWith(inlineRaw: object) {+ const inner = {+ getServer: jest.fn().mockResolvedValue(registryServer),+ listServers: jest.fn().mockResolvedValue([registryServer]),+ resolveInvokeHeaders: jest.fn().mockReturnValue({ Authorization: 'Bearer caller-token' }),+ resolveAuthStatuses: jest.fn().mockResolvedValue(new Map([['team-mcp', { status: 'not_required' }]])),+ } as unknown as IMcpServerWithAuthStore;+ const store = new InlineMcpServerStore({+ inner,+ inline: parseInlineMcpServers(JSON.stringify(inlineRaw)),+ });+ return { store, inner };+}++function skillStoreWith(inlineRaw: object, innerOverrides?: Partial<ISkillStore>) {+ const inner = {+ listSkills: jest.fn().mockResolvedValue([registrySkill]),+ validateAgentSkills: jest.fn().mockResolvedValue(undefined),+ resolveTurnSkills: jest.fn().mockResolvedValue([]),+ listSkillVersions: jest.fn().mockResolvedValue([]),+ ...innerOverrides,+ } as unknown as ISkillStore;+ const store = new InlineSkillStore({ inner, inline: parseInlineSkills(JSON.stringify(inlineRaw)) });+ return { store, inner };+}++describe('parseInlineMcpServers', () => {+ it('fills in the type and the name the caller left implicit', () => {+ expect(parseInlineMcpServers(JSON.stringify({ 'docs-mcp': DOCS_MCP }))).toEqual({+ 'docs-mcp': { ...DOCS_MCP, type: 'remote', name: 'docs-mcp' },+ });+ });++ it('rejects dcr auth, which has no registered client or stored token to use', () => {+ const raw = JSON.stringify({ 'docs-mcp': { ...DOCS_MCP, auth: { type: 'dcr' } } });++ expect(() => parseInlineMcpServers(raw)).toThrow(HTTPException);+ });++ it.each([+ ['not json', 'not-json'],+ ['an array', '[]'],+ ['a scalar', '"nope"'],+ ['a server mapped to a string', JSON.stringify({ 'docs-mcp': 'https://docs.example/mcp' })],+ ['a server with no url', JSON.stringify({ 'docs-mcp': { description: 'no url' } })],+ ['a name the registry would reject', JSON.stringify({ 'Docs MCP': DOCS_MCP })],+ ['an unknown field', JSON.stringify({ 'docs-mcp': { ...DOCS_MCP, preload: true } })],+ ])('rejects %s rather than falling back to a registry that has no such server', (_case, raw) => {+ expect(() => parseInlineMcpServers(raw)).toThrow(HTTPException);+ });++ it('keeps the parse failure as the cause, so a bad header can be debugged', () => {+ expect(() => parseInlineMcpServers('not-json')).toThrow(+ expect.objectContaining({ cause: expect.any(SyntaxError) }),+ );+ });+});++describe('parseInlineSkills', () => {+ it('fills in the type and the name the caller left implicit', () => {+ expect(parseInlineSkills(JSON.stringify({ 'ask-ai': ASK_AI_SKILL }))).toEqual({+ 'ask-ai': { ...ASK_AI_SKILL, type: 'git', name: 'ask-ai' },+ });+ });++ it.each([+ ['no ref, which would silently mount a moving HEAD', { url: ASK_AI_SKILL.url, description: 'no ref' }],+ ['a non-git host', { ...ASK_AI_SKILL, url: 'https://example.com/skills' }],+ ['a path escaping the repository', { ...ASK_AI_SKILL, path: '../secrets' }],+ ])('rejects a skill with %s', (_case, definition) => {+ expect(() => parseInlineSkills(JSON.stringify({ 'ask-ai': definition }))).toThrow(HTTPException);+ });+});++describe('InlineMcpServerStore', () => {+ it('sends the credentials the manifest carries, with no caller Bearer added over them', () => {+ const { store } = mcpStoreWith({ 'docs-mcp': DOCS_MCP });+ const record = { ...registryServer, name: 'docs-mcp' };++ expect(store.resolveInvokeHeaders({ record, userRef: 'user-1' })).toEqual({+ Authorization: 'Bearer saas-token',+ });+ });++ it('leaves a registry server to the store that knows how to authenticate it', () => {+ const { store, inner } = mcpStoreWith({ 'docs-mcp': DOCS_MCP });++ expect(store.resolveInvokeHeaders({ record: registryServer, userRef: 'user-1' })).toEqual({+ Authorization: 'Bearer caller-token',+ });+ expect(inner.resolveInvokeHeaders).toHaveBeenCalled();+ });++ it('resolves an inline server by name without asking the registry', async () => {+ const { store, inner } = mcpStoreWith({ 'docs-mcp': DOCS_MCP });++ const record = await store.getServer({ tenant_id: 'default', name: 'docs-mcp' });++ expect(record?.manifest.url).toBe(DOCS_MCP.url);+ expect(inner.getServer).not.toHaveBeenCalled();+ });++ it('falls through to the registry for a name the request did not bring', async () => {+ const { store } = mcpStoreWith({ 'docs-mcp': DOCS_MCP });++ expect(await store.getServer({ tenant_id: 'default', name: 'team-mcp' })).toEqual(registryServer);+ });++ it('does not treat Object.prototype keys as inline resources', async () => {+ const { store, inner } = mcpStoreWith({ 'docs-mcp': DOCS_MCP });++ await store.getServer({ tenant_id: 'default', name: 'constructor' });++ expect(inner.getServer).toHaveBeenCalledWith({ tenant_id: 'default', name: 'constructor' }, undefined);+ });++ it('answers a name-filtered list from both sources, which is what spec validation asks for', async () => {+ const { store } = mcpStoreWith({ 'docs-mcp': DOCS_MCP });++ const data = await store.listServers({+ tenant_id: 'default',+ names: ['docs-mcp', 'team-mcp'],+ });++ expect(data.map(record => record.name)).toEqual(['docs-mcp', 'team-mcp']);+ });++ it('keeps request-scoped servers out of an unfiltered list, so they never reach tenant settings', async () => {+ const { store } = mcpStoreWith({ 'docs-mcp': DOCS_MCP });++ const data = await store.listServers({+ tenant_id: 'default',+ names: undefined,+ });++ expect(data.map(record => record.name)).toEqual(['team-mcp']);+ });+});++describe('InlineSkillStore', () => {+ it('answers a name-filtered list from both sources', async () => {+ const { store } = skillStoreWith({ 'ask-ai': ASK_AI_SKILL });++ const records = await store.listSkills({ tenant_id: 'default', names: ['ask-ai', 'team-skill'] });++ expect(records.map(record => record.name)).toEqual(['ask-ai', 'team-skill']);+ });++ it('exposes the git mount fields that turn execution expands', async () => {+ const { store } = skillStoreWith({ 'ask-ai': ASK_AI_SKILL });++ const [record] = await store.listSkills({ tenant_id: 'default', names: ['ask-ai'] });++ expect(record?.manifest).toEqual({ ...ASK_AI_SKILL, type: 'git', name: 'ask-ai' });+ });++ it('keeps request-scoped skills out of an unfiltered list, so they never reach tenant settings', async () => {+ const { store } = skillStoreWith({ 'ask-ai': ASK_AI_SKILL });++ const records = await store.listSkills({ tenant_id: 'default', names: undefined });++ expect(records.map(record => record.name)).toEqual(['team-skill']);+ });++ it('validate allows mixed inline and registry skills; resolve rejects sandbox-name collisions', async () => {+ const registryFqn = 'agent-skill:acme/team-a/echo:3';+ const { store, inner } = skillStoreWith(+ { echo: { ...ASK_AI_SKILL, path: 'echo' } },+ {+ resolveTurnSkills: jest.fn().mockResolvedValue([+ {+ type: 'registry',+ name: 'echo',+ description: 'Registry echo',+ fqn: registryFqn,+ preload: false,+ skillMdContent: null,+ presignedUrl: 'https://example.com/echo.tgz',+ },+ ]),+ },+ );+ const skills = [+ { name: 'echo', preload: false },+ { name: registryFqn, preload: false },+ ];++ await expect(store.validateAgentSkills({ tenant_id: 'default', skills })).resolves.toBeUndefined();+ expect(inner.validateAgentSkills).toHaveBeenCalledWith(+ { tenant_id: 'default', skills: [{ name: registryFqn, preload: false }] },+ undefined,+ );+ expect(inner.resolveTurnSkills).not.toHaveBeenCalled();++ await expect(store.resolveTurnSkills({ tenant_id: 'default', skills })).rejects.toMatchObject({+ status: 422,+ message: 'Agent skills must have unique names; duplicate skill name(s): echo',+ });+ });+});