UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

168 lines • 7.73 kB
// skills-carry-MCP sidecar loader (todo 37). // // Skills can ship MCP servers two ways: an `mcp.json` sidecar next to SKILL.md // (Amp-compatible: a map of serverName -> {command/args/env | url/headers} plus // an optional includeTools glob list, optionally wrapped in `mcpServers`), or a // `mcp:` block in SKILL.md frontmatter. The sidecar wins when both exist. // Declared servers register LAZY with tools hidden (0 pre-load payload tokens, // enforced by resolveSkillMcpServer forcing search mode with no directTools); // loading a skill (a `/skill:<name>` command or the model reading its SKILL.md) // reveals the union of its includeTools matches for the session. The same // server declared by multiple skills union-merges includeTools; a name // collision with a system-configured server is resolved system-wins at // registration (service.attachSkillMcpServers). There is no reliable unload // signal, so revealed tools stay active for the session. import { existsSync, statSync } from "node:fs"; import { join } from "node:path"; import { parseFrontmatter } from "../../../../utils/frontmatter.js"; import { authorizeSkillPath, BlockedSkillLinkError, readSkillFileCheckedSync, } from "../../../skill-access.js"; export function parseSkillMcpDeclarations(skills) { const servers = new Map(); const warnings = []; for (const skill of skills) { const { declared, sourcePath, warning } = readSkillServers(skill); if (warning !== undefined) warnings.push(warning); for (const [name, raw] of Object.entries(declared)) { const globs = normalizeGlobs(raw.includeTools); const existing = servers.get(name); if (existing === undefined) { servers.set(name, { includeToolsBySkill: new Map([[skill.name, globs]]), raw, scope: skill.sourceInfo?.scope, skillName: skill.name, sourcePath, provenance: skill.provenance, allowedSet: skill.allowedSet, skillPath: skill.filePath, }); continue; } // Same server from multiple skills: first config wins, includeTools // union-merge per skill (revealed together once any owner loads). existing.includeToolsBySkill.set(skill.name, globs); } } return { servers, warnings }; } /** Parsed declarations per skill file, reused while the sidecar and the skill file are unchanged on disk. */ const skillServersCache = new Map(); function fileStamp(path) { try { const stat = statSync(path); return `${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.ino}`; } catch { return "missing"; } } /** * Called for every skill on every turn (before_agent_start), so re-reading and re-parsing each * SKILL.md stalled each turn; the stat key keeps edits on disk visible on the next turn. */ function readSkillServers(skill) { const sidecarPath = join(skill.baseDir, "mcp.json"); const key = `${fileStamp(sidecarPath)}|${fileStamp(skill.filePath)}|${JSON.stringify(skill.provenance)}|${skill.allowedSet?.digest ?? ""}`; const cached = skillServersCache.get(skill.filePath); if (cached?.key === key) { try { authorizeSkillPath(cached.servers.sourcePath, skill.provenance, skill.allowedSet); return cached.servers; } catch { // Authorization is not cached: re-reading below produces the retained warning. } } const servers = readSkillServersFromDisk(skill); skillServersCache.set(skill.filePath, { key, servers }); return servers; } function readSkillServersFromDisk(skill) { const sidecarPath = join(skill.baseDir, "mcp.json"); const project = skill.provenance === undefined ? skill.sourceInfo?.scope === "project" : skill.provenance.kind !== "user"; if (existsSync(sidecarPath)) { try { const parsed = JSON.parse(readSkillFileCheckedSync(sidecarPath, skill.provenance, skill.allowedSet)); return { declared: unwrapServerMap(parsed), sourcePath: sidecarPath }; } catch (error) { if (error instanceof BlockedSkillLinkError) return { declared: {}, sourcePath: sidecarPath, warning: error.message }; return { declared: {}, sourcePath: sidecarPath, warning: project ? `Skill '${skill.name}': invalid mcp.json sidecar skipped; the skill itself still loads.` : `Skill '${skill.name}': invalid mcp.json sidecar skipped (${error instanceof Error ? error.message : String(error)}); the skill itself still loads.`, }; } } try { const { frontmatter } = parseFrontmatter(readSkillFileCheckedSync(skill.filePath, skill.provenance, skill.allowedSet)); if (frontmatter.mcp === undefined) return { declared: {}, sourcePath: skill.filePath }; return { declared: unwrapServerMap(frontmatter.mcp), sourcePath: skill.filePath }; } catch (error) { if (error instanceof BlockedSkillLinkError) return { declared: {}, sourcePath: skill.filePath, warning: error.message }; return { declared: {}, sourcePath: skill.filePath, warning: project ? `Skill '${skill.name}': unreadable frontmatter mcp block skipped; the skill itself still loads.` : `Skill '${skill.name}': unreadable frontmatter mcp block skipped (${error instanceof Error ? error.message : String(error)}); the skill itself still loads.`, }; } } function unwrapServerMap(value) { if (typeof value !== "object" || value === null || Array.isArray(value)) return {}; const record = value; const map = typeof record.mcpServers === "object" && record.mcpServers !== null ? record.mcpServers : record; const declared = {}; for (const [name, server] of Object.entries(map)) { if (typeof server !== "object" || server === null || Array.isArray(server)) continue; declared[name] = server; } return declared; } function normalizeGlobs(includeTools) { if (!Array.isArray(includeTools)) return ["*"]; const globs = includeTools.filter((glob) => typeof glob === "string" && glob.length > 0); return globs.length > 0 ? globs : ["*"]; } /** `*`-only glob match against the ORIGINAL (server-side) tool name. */ export function matchIncludeTools(globs, toolName) { return globs.some((glob) => { const pattern = `^${glob.split("*").map(escapeRegExp).join(".*")}$`; return new RegExp(pattern).test(toolName); }); } function escapeRegExp(text) { return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } /** * Names to reveal when `skillName` loads: for every server the skill declared, * every REGISTERED tool (mapped `mcp_<server>_<tool>` name) whose server-side * tool name matches the union of that skill's includeTools globs. */ export function skillActivationTargets(declarations, skillName, registered) { const targets = new Set(); for (const [serverName, decl] of declarations.servers) { const globs = decl.includeToolsBySkill.get(skillName); if (globs === undefined) continue; for (const tool of registered) { if (tool.server !== serverName) continue; if (matchIncludeTools(globs, tool.toolName)) targets.add(tool.name); } } return [...targets].sort(); } //# sourceMappingURL=skills.js.map