@iconicompany/imcp 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -0
- package/package.json +1 -1
- package/src/index.ts +1 -0
- package/src/plugin.ts +105 -0
- package/src/service.ts +40 -5
- package/src/tool.ts +2 -0
package/README.md
CHANGED
|
@@ -34,6 +34,8 @@ const mcp = createMcpService({
|
|
|
34
34
|
description: "Статус заказа организации вызывающего",
|
|
35
35
|
input: z.object({ orderId: z.string() }),
|
|
36
36
|
readOnly: true,
|
|
37
|
+
// `_meta` в tools/list: признак клиента, например допуск во встроенный чат iagent.
|
|
38
|
+
meta: { "com.iconicompany.iagent/embed": true },
|
|
37
39
|
handler: async ({ orderId }, { caller }) => {
|
|
38
40
|
const order = await orders.find(caller.orgId, orderId);
|
|
39
41
|
if (!order) throw new ToolRefusal("Заказ не найден");
|
|
@@ -80,6 +82,23 @@ for (const p of mcp.paths.all) app.all(p, ({ request }) => mcp.fetch(request));
|
|
|
80
82
|
- `throw new ToolRefusal("текст")` — отказ модели с этим текстом. Любая другая ошибка уходит модели общим
|
|
81
83
|
текстом, в журнал — только её класс (`internal: Error`): в сообщениях бывают персональные данные.
|
|
82
84
|
- `role` у инструмента — инструмент виден только с этой ролью.
|
|
85
|
+
- `readOnly: true` — `annotations.readOnlyHint`; без него клиент считает инструмент пишущим (умолчание MCP).
|
|
86
|
+
- `meta` — `_meta` инструмента в `tools/list`, ключ — обратный домен. Встроенный чат iagent берёт инструмент
|
|
87
|
+
только с `meta: { "com.iconicompany.iagent/embed": true }` и `readOnly: true`.
|
|
88
|
+
|
|
89
|
+
## Плагин агента
|
|
90
|
+
|
|
91
|
+
Указания агента модуля живут в репозитории модуля в формате плагина Claude Code (`agent/.claude-plugin/plugin.json`,
|
|
92
|
+
`agent/skills/*/SKILL.md`, `agent/.mcp.json`) и отдаются iagent по `GET <basePath>/agent/plugin.json`:
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
plugin: loadPluginDir(`${import.meta.dir}/../agent`), // бинарник --compile: parsePlugin({ путь: текст }) из импортов файлов
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
- `plugin.json`: `name`, `version` (semver, поднимать при любой правке текста), `description`, `roles` — роли проекта,
|
|
99
|
+
без которых ручка отвечает 403 (как роль инструмента). Без токена — 401.
|
|
100
|
+
- Ответ: `{ name, version, description, roles, mcp: { url }, skills: [{ name, description, body }] }`, `body` — текст
|
|
101
|
+
SKILL.md без frontmatter. Кривой плагин (нет skills, пустой skill, версия не semver) — исключение при старте.
|
|
83
102
|
|
|
84
103
|
## Журнал
|
|
85
104
|
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
package/src/plugin.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
/** Плагин агента модуля (формат Claude Code: `.claude-plugin/plugin.json`, `skills/*\/SKILL.md`, `.mcp.json`). */
|
|
5
|
+
export interface AgentPlugin {
|
|
6
|
+
name: string;
|
|
7
|
+
version: string;
|
|
8
|
+
description?: string;
|
|
9
|
+
/** Роли проекта, без которых плагин не отдаётся (как роль инструмента). */
|
|
10
|
+
roles: string[];
|
|
11
|
+
mcp?: { url: string };
|
|
12
|
+
skills: { name: string; description: string; body: string }[];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
16
|
+
const fail = (why: string): never => {
|
|
17
|
+
throw new Error(`imcp: плагин — ${why}`);
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** SKILL.md: frontmatter `name`, `description` и текст после него. */
|
|
21
|
+
function skillOf(path: string, text: string): AgentPlugin["skills"][number] {
|
|
22
|
+
const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(text);
|
|
23
|
+
if (!m) return fail(`${path}: нет frontmatter`);
|
|
24
|
+
// Только однострочные значения: блок YAML (`>`, `|`) не разбираем — отказ, а не «>-» в описании.
|
|
25
|
+
const field = (key: string) => {
|
|
26
|
+
const value = new RegExp(`^${key}:[ \\t]*(.*)$`, "m").exec(m[1]!)?.[1]?.trim() ?? "";
|
|
27
|
+
if (/^[>|]/.test(value)) fail(`${path}: ${key} — блок YAML, нужна одна строка`);
|
|
28
|
+
const quoted = /^(["'])(.*)\1$/.exec(value);
|
|
29
|
+
return quoted ? quoted[2]! : value;
|
|
30
|
+
};
|
|
31
|
+
const skill = { name: field("name"), description: field("description"), body: m[2]!.trim() };
|
|
32
|
+
if (!skill.name || !skill.description || !skill.body)
|
|
33
|
+
fail(`${path}: пустые name, description или текст`);
|
|
34
|
+
return skill;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Файлы плагина (путь от его каталога → текст) → плагин. Кривой — исключение: модуль не стартует. */
|
|
38
|
+
export function parsePlugin(files: Record<string, string>): AgentPlugin {
|
|
39
|
+
const raw = files[".claude-plugin/plugin.json"] ?? fail("нет .claude-plugin/plugin.json");
|
|
40
|
+
let manifest: Record<string, unknown>;
|
|
41
|
+
try {
|
|
42
|
+
manifest = JSON.parse(raw) as Record<string, unknown>;
|
|
43
|
+
} catch {
|
|
44
|
+
return fail(".claude-plugin/plugin.json — не JSON");
|
|
45
|
+
}
|
|
46
|
+
const name = typeof manifest.name === "string" ? manifest.name : "";
|
|
47
|
+
const version = typeof manifest.version === "string" ? manifest.version : "";
|
|
48
|
+
if (!name) fail("нет name");
|
|
49
|
+
if (!SEMVER.test(version)) fail(`version «${version}» — не semver`);
|
|
50
|
+
// Роли обязательны: без них ручка отдала бы указания агента любому токену аудитории.
|
|
51
|
+
const roles = manifest.roles;
|
|
52
|
+
if (
|
|
53
|
+
!Array.isArray(roles) ||
|
|
54
|
+
roles.length === 0 ||
|
|
55
|
+
!roles.every((r) => typeof r === "string" && r !== "")
|
|
56
|
+
)
|
|
57
|
+
fail("roles — непустой список ролей проекта");
|
|
58
|
+
const skills = Object.keys(files)
|
|
59
|
+
.filter((p) => /^skills\/[^/]+\/SKILL\.md$/.test(p))
|
|
60
|
+
.sort()
|
|
61
|
+
.map((p) => skillOf(p, files[p]!));
|
|
62
|
+
if (skills.length === 0) fail("нет skills/*/SKILL.md");
|
|
63
|
+
const names = skills.map((k) => k.name);
|
|
64
|
+
const twice = names.find((n, i) => names.indexOf(n) !== i);
|
|
65
|
+
if (twice) fail(`skill ${twice} — дважды`);
|
|
66
|
+
let mcp: AgentPlugin["mcp"];
|
|
67
|
+
if (files[".mcp.json"]) {
|
|
68
|
+
let servers: Record<string, unknown>;
|
|
69
|
+
try {
|
|
70
|
+
servers = ((JSON.parse(files[".mcp.json"]) as { mcpServers?: Record<string, unknown> })
|
|
71
|
+
.mcpServers ?? {}) as Record<string, unknown>;
|
|
72
|
+
} catch {
|
|
73
|
+
return fail(".mcp.json — не JSON");
|
|
74
|
+
}
|
|
75
|
+
const url = Object.values(servers)
|
|
76
|
+
.map((v) => (v && typeof v === "object" ? (v as { url?: unknown }).url : undefined))
|
|
77
|
+
.find((u): u is string => typeof u === "string");
|
|
78
|
+
if (url) mcp = { url };
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
name,
|
|
82
|
+
version,
|
|
83
|
+
...(typeof manifest.description === "string" && { description: manifest.description }),
|
|
84
|
+
roles: roles as string[],
|
|
85
|
+
...(mcp && { mcp }),
|
|
86
|
+
skills,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Каталог плагина на диске → плагин. В бинарнике `bun build --compile` каталога нет: там — `parsePlugin` с импортом файлов. */
|
|
91
|
+
export function loadPluginDir(dir: string): AgentPlugin {
|
|
92
|
+
// Только файлы плагина: скрипты и картинки skills не читаем, по ссылкам не ходим.
|
|
93
|
+
const files: Record<string, string> = {};
|
|
94
|
+
for (const path of [".claude-plugin/plugin.json", ".mcp.json"])
|
|
95
|
+
if (existsSync(join(dir, path))) files[path] = readFileSync(join(dir, path), "utf8");
|
|
96
|
+
const skillsDir = join(dir, "skills");
|
|
97
|
+
if (existsSync(skillsDir))
|
|
98
|
+
for (const entry of readdirSync(skillsDir, { withFileTypes: true }))
|
|
99
|
+
if (entry.isDirectory() && existsSync(join(skillsDir, entry.name, "SKILL.md")))
|
|
100
|
+
files[`skills/${entry.name}/SKILL.md`] = readFileSync(
|
|
101
|
+
join(skillsDir, entry.name, "SKILL.md"),
|
|
102
|
+
"utf8",
|
|
103
|
+
);
|
|
104
|
+
return parsePlugin(files);
|
|
105
|
+
}
|
package/src/service.ts
CHANGED
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
|
|
8
8
|
import { createVerifier, type Caller, type ZitadelAuthOptions } from "./bearer";
|
|
9
9
|
import { callLine, type CallLine } from "./log";
|
|
10
|
+
import type { AgentPlugin } from "./plugin";
|
|
10
11
|
import { isRefusal, refusalResult, toResult, type ToolDefinition } from "./tool";
|
|
11
12
|
|
|
12
13
|
export interface McpServiceOptions {
|
|
@@ -25,6 +26,8 @@ export interface McpServiceOptions {
|
|
|
25
26
|
// Инструменты разных схем: тип аргументов проверен в defineTool.
|
|
26
27
|
// oxlint-disable-next-line no-explicit-any
|
|
27
28
|
tools: ToolDefinition<any>[];
|
|
29
|
+
/** Плагин агента модуля: отдаётся на `<basePath>/agent/plugin.json` тем, у кого все его роли. */
|
|
30
|
+
plugin?: AgentPlugin;
|
|
28
31
|
/** Журнал вызовов инструментов; по умолчанию — строка JSON в stdout. */
|
|
29
32
|
log?: (line: CallLine) => void;
|
|
30
33
|
}
|
|
@@ -65,6 +68,7 @@ export function mcpPaths(o: Pick<McpServiceOptions, "basePath" | "mcpPath">) {
|
|
|
65
68
|
mcp,
|
|
66
69
|
health: `${base}/health`,
|
|
67
70
|
card: `${base}/.well-known/mcp/server-card.json`,
|
|
71
|
+
plugin: `${base}/agent/plugin.json`,
|
|
68
72
|
metadata,
|
|
69
73
|
metadataPaths: [...new Set([metadata, `${base}${metadata}`])],
|
|
70
74
|
};
|
|
@@ -138,6 +142,7 @@ export function createMcpService(options: McpServiceOptions) {
|
|
|
138
142
|
description: tool.description,
|
|
139
143
|
inputSchema: tool.input,
|
|
140
144
|
...(tool.readOnly !== undefined && { annotations: { readOnlyHint: tool.readOnly } }),
|
|
145
|
+
...(tool.meta && { _meta: { ...tool.meta } }),
|
|
141
146
|
},
|
|
142
147
|
async (args: unknown) => {
|
|
143
148
|
const started = performance.now();
|
|
@@ -175,7 +180,11 @@ export function createMcpService(options: McpServiceOptions) {
|
|
|
175
180
|
},
|
|
176
181
|
);
|
|
177
182
|
|
|
178
|
-
|
|
183
|
+
/** Токен и роли: вызывающий или готовый отказ — одна проверка для MCP и плагина. */
|
|
184
|
+
async function authenticate(
|
|
185
|
+
request: Request,
|
|
186
|
+
roles: (string | undefined)[],
|
|
187
|
+
): Promise<{ token: string; caller: Caller } | Response> {
|
|
179
188
|
const header = request.headers.get("authorization") ?? "";
|
|
180
189
|
const token = /^Bearer\s+/i.test(header) ? header.replace(/^Bearer\s+/i, "").trim() : "";
|
|
181
190
|
if (!token) return challenge(401, null, "нужен токен: Authorization: Bearer <token>");
|
|
@@ -187,9 +196,15 @@ export function createMcpService(options: McpServiceOptions) {
|
|
|
187
196
|
"invalid_token",
|
|
188
197
|
"токен не принят: подпись, издатель, аудитория или срок",
|
|
189
198
|
);
|
|
190
|
-
const
|
|
191
|
-
if (
|
|
192
|
-
|
|
199
|
+
const missing = roles.find((r) => r && !caller.roles.includes(r));
|
|
200
|
+
if (missing) return challenge(403, "insufficient_scope", `нет роли проекта ${missing}`);
|
|
201
|
+
return { token, caller };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function serveMcp(request: Request): Promise<Response> {
|
|
205
|
+
const auth = await authenticate(request, [options.auth.role]);
|
|
206
|
+
if (auth instanceof Response) return auth;
|
|
207
|
+
const { token, caller } = auth;
|
|
193
208
|
const authInfo: AuthInfo = {
|
|
194
209
|
token,
|
|
195
210
|
clientId: caller.clientId,
|
|
@@ -206,6 +221,16 @@ export function createMcpService(options: McpServiceOptions) {
|
|
|
206
221
|
return new Response(response.body, { status: response.status, headers });
|
|
207
222
|
}
|
|
208
223
|
|
|
224
|
+
// Плагин — указания агента: только служебной учётке с ролями из манифеста, как инструменты.
|
|
225
|
+
// Адрес MCP — свой, из настроек сервиса: .mcp.json репозитория мог указывать на другое окружение.
|
|
226
|
+
async function servePlugin(request: Request, plugin: AgentPlugin): Promise<Response> {
|
|
227
|
+
const auth = await authenticate(request, [options.auth.role, ...plugin.roles]);
|
|
228
|
+
if (auth instanceof Response) return auth;
|
|
229
|
+
return json({ ...plugin, mcp: { url: `${origin}${paths.mcp}` } }, 200, {
|
|
230
|
+
"cache-control": "no-store",
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
|
|
209
234
|
const publicDoc = (body: unknown) => json(body, 200, { "cache-control": "public, max-age=300" });
|
|
210
235
|
|
|
211
236
|
async function fetch(request: Request): Promise<Response> {
|
|
@@ -217,13 +242,23 @@ export function createMcpService(options: McpServiceOptions) {
|
|
|
217
242
|
if (path === paths.health)
|
|
218
243
|
return json({ ok: true, name: options.name, version: options.version });
|
|
219
244
|
if (path === paths.card) return publicDoc(card);
|
|
245
|
+
if (options.plugin && path === paths.plugin) return servePlugin(request, options.plugin);
|
|
220
246
|
if (paths.metadataPaths.includes(path)) return publicDoc(metadata);
|
|
221
247
|
return json({ error: "not_found" }, 404);
|
|
222
248
|
}
|
|
223
249
|
|
|
224
250
|
return {
|
|
225
251
|
fetch,
|
|
226
|
-
paths: {
|
|
252
|
+
paths: {
|
|
253
|
+
...paths,
|
|
254
|
+
all: [
|
|
255
|
+
paths.mcp,
|
|
256
|
+
paths.health,
|
|
257
|
+
paths.card,
|
|
258
|
+
...paths.metadataPaths,
|
|
259
|
+
...(options.plugin ? [paths.plugin] : []),
|
|
260
|
+
],
|
|
261
|
+
},
|
|
227
262
|
card,
|
|
228
263
|
close: () => mcp.close(),
|
|
229
264
|
};
|
package/src/tool.ts
CHANGED
|
@@ -27,6 +27,8 @@ export interface ToolDefinition<S extends z.ZodObject = z.ZodObject> {
|
|
|
27
27
|
input: S;
|
|
28
28
|
/** Только чтение — подсказка клиенту (`readOnlyHint`). */
|
|
29
29
|
readOnly?: boolean;
|
|
30
|
+
/** `_meta` инструмента в `tools/list`: признаки клиентов (ключ — обратный домен, `com.iconicompany.iagent/embed`). */
|
|
31
|
+
meta?: Record<string, unknown>;
|
|
30
32
|
/** Роль проекта сверх роли сервиса; без неё инструмента в списке нет. */
|
|
31
33
|
role?: string;
|
|
32
34
|
handler: (args: z.infer<S>, ctx: ToolContext) => Promise<ToolReturn> | ToolReturn;
|