@datacules/agent-identity-mcp 0.10.0 → 0.11.1

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/LICENSE ADDED
@@ -0,0 +1,109 @@
1
+ Datacules Agent Identity License — Version 1.0
2
+ Copyright (c) 2026 Datacules LLC. All rights reserved.
3
+
4
+ ─────────────────────────────────────────────────────────────────────────────
5
+ PREAMBLE
6
+ ─────────────────────────────────────────────────────────────────────────────
7
+
8
+ This software — Agent Identity & Auth Patterns — is developed and owned by
9
+ Datacules LLC. It is made available to the public as open-source software
10
+ under the permissive terms below.
11
+
12
+ Datacules LLC retains ownership and authorship of this software while
13
+ granting broad, royalty-free rights for anyone to use, copy, modify, and
14
+ distribute it — in commercial or non-commercial contexts — without requiring
15
+ that derivative works also become open source.
16
+
17
+ ─────────────────────────────────────────────────────────────────────────────
18
+ TERMS AND CONDITIONS
19
+ ─────────────────────────────────────────────────────────────────────────────
20
+
21
+ 1. PERMISSION TO USE
22
+
23
+ Permission is hereby granted, free of charge, to any person or
24
+ organization obtaining a copy of this software and associated
25
+ documentation files (the "Software"), to use, copy, modify, merge,
26
+ publish, distribute, sublicense, and/or sell copies of the Software,
27
+ and to permit persons to whom the Software is furnished to do so,
28
+ subject to the conditions below.
29
+
30
+ 2. ATTRIBUTION
31
+
32
+ a. Redistributions of source code must retain this copyright notice,
33
+ this list of conditions, and the disclaimer below.
34
+
35
+ b. Redistributions in binary form or as a product must reproduce this
36
+ copyright notice, this list of conditions, and the disclaimer in the
37
+ documentation and/or other materials provided with the distribution.
38
+
39
+ c. Neither the name "Datacules LLC" nor the names of its contributors
40
+ may be used to endorse or promote products derived from this Software
41
+ without prior written permission from Datacules LLC.
42
+
43
+ 3. COMMERCIAL USE
44
+
45
+ Use of this Software in commercial products, SaaS platforms, internal
46
+ enterprise tools, or any revenue-generating context is explicitly
47
+ permitted without royalty, fee, or additional licensing agreement,
48
+ provided that the conditions in Section 2 (Attribution) are met.
49
+
50
+ 4. NO COPYLEFT / NO VIRAL REQUIREMENT
51
+
52
+ This license does NOT require that derivative works, modifications,
53
+ or software that uses or embeds this Software be made open source.
54
+ You may incorporate this Software into proprietary or closed-source
55
+ products under your own license terms.
56
+
57
+ 5. MODIFICATIONS
58
+
59
+ Modified versions of the Software may be distributed under the same
60
+ terms as this license or under any other permissive open-source
61
+ license (e.g. MIT, Apache 2.0, BSD), provided that:
62
+
63
+ a. The original copyright notice of Datacules LLC is preserved.
64
+ b. Modifications are clearly documented and distinguished from the
65
+ original work.
66
+
67
+ 6. COMPATIBILITY
68
+
69
+ This license is compatible with other permissive open-source licenses
70
+ such as MIT, BSD 2-Clause, BSD 3-Clause, and Apache License 2.0. It
71
+ is also GPL-compatible — this Software may coexist with GPL-licensed
72
+ code, though this Software itself is not distributed under the GPL.
73
+
74
+ ─────────────────────────────────────────────────────────────────────────────
75
+ DISCLAIMER
76
+ ─────────────────────────────────────────────────────────────────────────────
77
+
78
+ THIS SOFTWARE IS PROVIDED BY DATACULES LLC AND CONTRIBUTORS "AS IS" AND
79
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80
+ IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
81
+ AND NON-INFRINGEMENT ARE DISCLAIMED.
82
+
83
+ IN NO EVENT SHALL DATACULES LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
84
+ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
85
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
86
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
87
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
88
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
89
+ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
90
+
91
+ ─────────────────────────────────────────────────────────────────────────────
92
+ SUMMARY (non-binding)
93
+ ─────────────────────────────────────────────────────────────────────────────
94
+
95
+ ✔ Use freely — commercial, proprietary, or open-source projects
96
+ ✔ Modify and distribute with or without changes
97
+ ✔ Sell products built on this Software
98
+ ✔ No royalties or fees
99
+ ✔ No requirement to open-source your own code
100
+ ✔ Attribution to Datacules LLC required in source and binary distributions
101
+ ✗ Do not use "Datacules LLC" to endorse derived products without permission
102
+
103
+ ─────────────────────────────────────────────────────────────────────────────
104
+ CONTACT
105
+ ─────────────────────────────────────────────────────────────────────────────
106
+
107
+ Datacules LLC
108
+ For licensing enquiries: legal@datacules.com
109
+ Product: https://github.com/hvrcharon1/agent-identity
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ /**
3
+ * @datacules/agent-identity-mcp
4
+ *
5
+ * Exposes agent-identity credential resolution as an MCP server.
6
+ * Any MCP-capable client — Claude Desktop, Claude Code, Cursor,
7
+ * Windsurf, or a custom agent — can call the following tools:
8
+ *
9
+ * resolve_credential — resolves a credential for an AgentRequestContext
10
+ * resolve_migration_credential — resolves source+target pair for MigrationContext
11
+ * list_credentials — lists active credentials (safe metadata only)
12
+ * list_rules — lists routing rules (highest priority first)
13
+ * health — liveness + loaded credential/rule counts
14
+ *
15
+ * Supports two transports:
16
+ * stdio — stdin/stdout, compatible with Claude Desktop / Claude Code / Cursor configs
17
+ * http+sse — HTTP Server-Sent Events for hosted deployments
18
+ *
19
+ * Quick start (stdio):
20
+ * import { createAgentIdentityMcpServer } from '@datacules/agent-identity-mcp';
21
+ * const { start } = createAgentIdentityMcpServer({ credentials, rules });
22
+ * await start(); // reads from stdin, writes to stdout
23
+ *
24
+ * Quick start (HTTP):
25
+ * const { start } = createAgentIdentityMcpServer({
26
+ * credentials, rules, transport: 'http', httpPort: 3002
27
+ * });
28
+ * await start();
29
+ *
30
+ * Claude Desktop config snippet (~/.claude/claude_desktop_config.json):
31
+ * {
32
+ * "mcpServers": {
33
+ * "agent-identity": {
34
+ * "command": "npx",
35
+ * "args": ["@datacules/agent-identity-mcp"],
36
+ * "env": {
37
+ * "AGENT_IDENTITY_CREDENTIALS": "<base64-encoded JSON>",
38
+ * "AGENT_IDENTITY_RULES": "<base64-encoded JSON>"
39
+ * }
40
+ * }
41
+ * }
42
+ * }
43
+ */
44
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
45
+ if (k2 === undefined) k2 = k;
46
+ var desc = Object.getOwnPropertyDescriptor(m, k);
47
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
48
+ desc = { enumerable: true, get: function() { return m[k]; } };
49
+ }
50
+ Object.defineProperty(o, k2, desc);
51
+ }) : (function(o, m, k, k2) {
52
+ if (k2 === undefined) k2 = k;
53
+ o[k2] = m[k];
54
+ }));
55
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
56
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
57
+ };
58
+ Object.defineProperty(exports, "__esModule", { value: true });
59
+ exports.ALL_TOOLS = void 0;
60
+ exports.createAgentIdentityMcpServer = createAgentIdentityMcpServer;
61
+ const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
62
+ const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
63
+ const agent_identity_1 = require("@datacules/agent-identity");
64
+ const tools_js_1 = require("./tools.js");
65
+ const transports_js_1 = require("./transports.js");
66
+ __exportStar(require("./types.js"), exports);
67
+ var tools_js_2 = require("./tools.js");
68
+ Object.defineProperty(exports, "ALL_TOOLS", { enumerable: true, get: function () { return tools_js_2.ALL_TOOLS; } });
69
+ /**
70
+ * Create an agent-identity MCP server.
71
+ *
72
+ * @example
73
+ * // stdio (Claude Desktop / Claude Code config)
74
+ * const { start } = createAgentIdentityMcpServer({ credentials, rules });
75
+ * await start();
76
+ *
77
+ * @example
78
+ * // HTTP+SSE (hosted / networked)
79
+ * const { start } = createAgentIdentityMcpServer({
80
+ * credentials, rules, transport: 'http', httpPort: 3002,
81
+ * });
82
+ * await start();
83
+ */
84
+ function createAgentIdentityMcpServer(config) {
85
+ const { credentials, store: customStore, rules, logger, name = 'agent-identity', version = '0.1.0', transport = 'stdio', httpPort = 3002, httpHost = '127.0.0.1', httpAuthToken, } = config;
86
+ if (!customStore && !credentials) {
87
+ throw new Error('[agent-identity-mcp] Provide either credentials[] or a custom store.');
88
+ }
89
+ const store = customStore ?? new agent_identity_1.MemoryCredentialStore(credentials);
90
+ const deps = { store, rules, logger };
91
+ // Build the MCP server
92
+ const server = new index_js_1.Server({ name, version }, { capabilities: { tools: {} } });
93
+ // Register tools/list handler
94
+ server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
95
+ tools: tools_js_1.ALL_TOOLS.map((t) => ({
96
+ name: t.name,
97
+ description: t.description,
98
+ inputSchema: {
99
+ type: 'object',
100
+ // Convert Zod schema to JSON Schema via .shape introspection for
101
+ // simple objects; complex schemas fall back to an open object.
102
+ properties: extractJsonSchemaProperties(t.inputSchema),
103
+ required: extractRequiredKeys(t.inputSchema),
104
+ },
105
+ })),
106
+ }));
107
+ // Register tools/call handler
108
+ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
109
+ const tool = tools_js_1.ALL_TOOLS.find((t) => t.name === request.params.name);
110
+ if (!tool) {
111
+ return {
112
+ content: [{ type: 'text', text: JSON.stringify({ error: `Unknown tool: ${request.params.name}` }) }],
113
+ isError: true,
114
+ };
115
+ }
116
+ return tool.handler(request.params.arguments ?? {}, deps);
117
+ });
118
+ let stopFn = null;
119
+ const start = async () => {
120
+ if (transport === 'stdio') {
121
+ const stdioTransport = new transports_js_1.StdioServerTransport();
122
+ await server.connect(stdioTransport);
123
+ }
124
+ else {
125
+ stopFn = await (0, transports_js_1.startHttpMcpTransport)({
126
+ server,
127
+ port: httpPort,
128
+ host: httpHost,
129
+ authToken: httpAuthToken,
130
+ });
131
+ }
132
+ };
133
+ const stop = async () => {
134
+ stopFn?.();
135
+ await server.close();
136
+ };
137
+ return { server, start, stop };
138
+ }
139
+ // ─── JSON Schema helpers (lightweight — no ajv dependency) ───────────────────
140
+ function extractJsonSchemaProperties(schema) {
141
+ try {
142
+ const shape = schema?._def?.shape?.() ?? schema?.shape ?? {};
143
+ const props = {};
144
+ for (const [key, val] of Object.entries(shape)) {
145
+ props[key] = zodToJsonSchemaNode(val);
146
+ }
147
+ return props;
148
+ }
149
+ catch {
150
+ return {};
151
+ }
152
+ }
153
+ function extractRequiredKeys(schema) {
154
+ try {
155
+ const shape = schema?._def?.shape?.() ?? schema?.shape ?? {};
156
+ return Object.entries(shape)
157
+ .filter(([, v]) => {
158
+ const typeName = v?._def?.typeName;
159
+ return typeName !== 'ZodOptional' && typeName !== 'ZodDefault';
160
+ })
161
+ .map(([k]) => k);
162
+ }
163
+ catch {
164
+ return [];
165
+ }
166
+ }
167
+ function zodToJsonSchemaNode(zodNode) {
168
+ const typeName = zodNode?._def?.typeName;
169
+ switch (typeName) {
170
+ case 'ZodString': return { type: 'string' };
171
+ case 'ZodNumber': return { type: 'number' };
172
+ case 'ZodBoolean': return { type: 'boolean' };
173
+ case 'ZodEnum': return { type: 'string', enum: zodNode._def.values };
174
+ case 'ZodOptional':
175
+ case 'ZodDefault': return zodToJsonSchemaNode(zodNode._def.innerType);
176
+ case 'ZodObject': return { type: 'object', properties: extractJsonSchemaProperties(zodNode) };
177
+ default: return { type: 'string' };
178
+ }
179
+ }
180
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;;;;;;;;;;;;;;;;;AAwDH,oEAgFC;AAtID,wEAAmE;AACnE,iEAG4C;AAE5C,8DAAkE;AAClE,yCAA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QAAQ,CAAC;IACzC,QAAQ,QAAQ,EAAE,CAAC;QACjB,KAAK,WAAW,CAAC,CAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QAC7C,KAAK,WAAW,CAAC,CAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QAC7C,KAAK,YAAY,CAAC,CAAC,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;QAC9C,KAAK,SAAS,CAAC,CAAI,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;QACxE,KAAK,aAAa,CAAC;QACnB,KAAK,YAAY,CAAC,CAAC,OAAO,mBAAmB,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACtE,KAAK,WAAW,CAAC,CAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,2BAA2B,CAAC,OAAO,CAAC,EAAE,CAAC;QAC/F,OAAO,CAAC,CAAW,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;IAC/C,CAAC;AACH,CAAC"}
@@ -0,0 +1,166 @@
1
+ "use strict";
2
+ /**
3
+ * MCP tool handler implementations for @datacules/agent-identity.
4
+ *
5
+ * Each exported function corresponds to one MCP tool:
6
+ * resolve_credential — resolves credential for AgentRequestContext
7
+ * resolve_migration_credential — resolves source+target pair for MigrationContext
8
+ * list_credentials — lists active credentials (safe metadata, no raw refs)
9
+ * list_rules — lists routing rules
10
+ * health — liveness check
11
+ *
12
+ * Tool schemas use Zod and are exported as McpToolSchema objects so the
13
+ * server index can register them with a single loop.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.ALL_TOOLS = void 0;
17
+ const zod_1 = require("zod");
18
+ const agent_identity_1 = require("@datacules/agent-identity");
19
+ // ─── Shared Zod schemas ───────────────────────────────────────────────────────
20
+ const SupportedProviderSchema = zod_1.z.enum(['openai', 'anthropic', 'gemini', 'mistral', 'local']);
21
+ const ResourceKindSchema = zod_1.z.enum(['shared', 'personal']);
22
+ const MigrationPhaseSchema = zod_1.z.enum(['dry-run', 'extract', 'transform', 'load', 'verify', 'rollback']);
23
+ const BaseContextSchema = zod_1.z.object({
24
+ userId: zod_1.z.string().min(1),
25
+ resourceId: zod_1.z.string().min(1),
26
+ resourceKind: ResourceKindSchema,
27
+ provider: SupportedProviderSchema,
28
+ model: zod_1.z.string().min(1),
29
+ action: zod_1.z.string().min(1),
30
+ traceId: zod_1.z.string().min(1),
31
+ sessionId: zod_1.z.string().optional(),
32
+ requestedAt: zod_1.z.string().optional(),
33
+ parentTraceId: zod_1.z.string().optional(),
34
+ mcpSessionId: zod_1.z.string().optional(),
35
+ mcpClientId: zod_1.z.string().optional(),
36
+ });
37
+ const ResolveCredentialSchema = BaseContextSchema;
38
+ const ResolveMigrationSchema = BaseContextSchema.extend({
39
+ migrationId: zod_1.z.string().min(1),
40
+ phase: MigrationPhaseSchema,
41
+ sourceResourceId: zod_1.z.string().min(1),
42
+ targetResourceId: zod_1.z.string().min(1),
43
+ batchIndex: zod_1.z.number().int().nonnegative().optional(),
44
+ totalBatches: zod_1.z.number().int().positive().optional(),
45
+ dryRun: zod_1.z.boolean(),
46
+ });
47
+ // ─── Helper ───────────────────────────────────────────────────────────────────
48
+ function ok(data) {
49
+ return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
50
+ }
51
+ function err(message) {
52
+ return { content: [{ type: 'text', text: JSON.stringify({ error: message }) }], isError: true };
53
+ }
54
+ // ─── resolve_credential ───────────────────────────────────────────────────────
55
+ const resolveCredentialTool = {
56
+ name: 'resolve_credential',
57
+ description: 'Resolve the correct credential for an agent request. ' +
58
+ 'Provide the full AgentRequestContext (userId, resourceId, resourceKind, provider, model, action, traceId). ' +
59
+ 'Returns the resolved credential metadata — never the raw secret.',
60
+ inputSchema: ResolveCredentialSchema,
61
+ async handler(input, { store, rules, logger }) {
62
+ const parsed = ResolveCredentialSchema.safeParse(input);
63
+ if (!parsed.success)
64
+ return err(`Validation error: ${parsed.error.message}`);
65
+ const ctx = {
66
+ ...parsed.data,
67
+ requestedAt: parsed.data.requestedAt ?? new Date().toISOString(),
68
+ };
69
+ const router = (0, agent_identity_1.createRouterFromStore)(store, rules, logger);
70
+ const resolved = router.resolve(ctx);
71
+ if (!resolved)
72
+ return err('No credential resolved — no routing rule matched this context.');
73
+ return ok({
74
+ ok: true,
75
+ credentialId: resolved.credentialId,
76
+ kind: resolved.kind,
77
+ resolvedFor: resolved.resolvedFor,
78
+ // ref is intentionally omitted — never surface raw refs over MCP
79
+ });
80
+ },
81
+ };
82
+ // ─── resolve_migration_credential ─────────────────────────────────────────────
83
+ const resolveMigrationCredentialTool = {
84
+ name: 'resolve_migration_credential',
85
+ description: 'Resolve source and target credentials for a data migration workflow. ' +
86
+ 'Requires a full MigrationContext including migrationId, phase, sourceResourceId, targetResourceId, and dryRun flag. ' +
87
+ 'Returns both resolved credential metadata objects — never raw secrets.',
88
+ inputSchema: ResolveMigrationSchema,
89
+ async handler(input, { store, rules, logger }) {
90
+ const parsed = ResolveMigrationSchema.safeParse(input);
91
+ if (!parsed.success)
92
+ return err(`Validation error: ${parsed.error.message}`);
93
+ const ctx = {
94
+ ...parsed.data,
95
+ requestedAt: parsed.data.requestedAt ?? new Date().toISOString(),
96
+ };
97
+ const router = (0, agent_identity_1.createRouterFromStore)(store, rules, logger);
98
+ const pair = router.resolvePair(ctx);
99
+ if (!pair)
100
+ return err('No credential pair resolved — check that routing rules cover both sourceResourceId and targetResourceId.');
101
+ return ok({
102
+ ok: true,
103
+ migrationId: pair.migrationId,
104
+ source: { credentialId: pair.source.credentialId, kind: pair.source.kind, resolvedFor: pair.source.resolvedFor },
105
+ target: { credentialId: pair.target.credentialId, kind: pair.target.kind, resolvedFor: pair.target.resolvedFor },
106
+ expiresAt: pair.expiresAt ?? null,
107
+ });
108
+ },
109
+ };
110
+ // ─── list_credentials ─────────────────────────────────────────────────────────
111
+ const listCredentialsTool = {
112
+ name: 'list_credentials',
113
+ description: 'List all active credentials registered with this agent-identity server. ' +
114
+ 'Returns safe metadata only (id, kind, name, scope, status, expiresAt). ' +
115
+ 'Raw refs and secrets are never included.',
116
+ inputSchema: zod_1.z.object({
117
+ kind: zod_1.z.enum(['fixed', 'user-delegated']).optional().describe('Filter by credential kind'),
118
+ }),
119
+ async handler(input, { store }) {
120
+ const parsed = zod_1.z.object({ kind: zod_1.z.enum(['fixed', 'user-delegated']).optional() }).safeParse(input);
121
+ if (!parsed.success)
122
+ return err(`Validation error: ${parsed.error.message}`);
123
+ const creds = parsed.data.kind
124
+ ? await store.listByKind(parsed.data.kind)
125
+ : await store.listActive();
126
+ const safe = creds.map(({ id, kind, name, scope, status, expiresAt }) => ({
127
+ id, kind, name, scope, status, expiresAt: expiresAt ?? null,
128
+ }));
129
+ return ok({ count: safe.length, credentials: safe });
130
+ },
131
+ };
132
+ // ─── list_rules ───────────────────────────────────────────────────────────────
133
+ const listRulesTool = {
134
+ name: 'list_rules',
135
+ description: 'List all routing rules registered with this agent-identity server, ' +
136
+ 'ordered by priority (highest first). Useful for debugging credential routing.',
137
+ inputSchema: zod_1.z.object({}),
138
+ async handler(_input, { rules }) {
139
+ const sorted = [...rules].sort((a, b) => b.priority - a.priority);
140
+ return ok({ count: sorted.length, rules: sorted });
141
+ },
142
+ };
143
+ // ─── health ───────────────────────────────────────────────────────────────────
144
+ const healthTool = {
145
+ name: 'health',
146
+ description: 'Check whether the agent-identity MCP server is healthy and how many credentials/rules are loaded.',
147
+ inputSchema: zod_1.z.object({}),
148
+ async handler(_input, { store, rules }) {
149
+ const active = await store.listActive();
150
+ return ok({
151
+ status: 'ok',
152
+ credentialsLoaded: active.length,
153
+ rulesLoaded: rules.length,
154
+ timestamp: new Date().toISOString(),
155
+ });
156
+ },
157
+ };
158
+ // ─── Export all tools ─────────────────────────────────────────────────────────
159
+ exports.ALL_TOOLS = [
160
+ resolveCredentialTool,
161
+ resolveMigrationCredentialTool,
162
+ listCredentialsTool,
163
+ listRulesTool,
164
+ healthTool,
165
+ ];
166
+ //# sourceMappingURL=tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.js","sourceRoot":"","sources":["../../src/tools.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;GAYG;;;AAEH,6BAAwB;AACxB,8DAAyF;AAQzF,iFAAiF;AAEjF,MAAM,uBAAuB,GAAG,OAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,WAAW,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC;AAC9F,MAAM,kBAAkB,GAAG,OAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC;AAC1D,MAAM,oBAAoB,GAAG,OAAC,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC;AAEvG,MAAM,iBAAiB,GAAG,OAAC,CAAC,MAAM,CAAC;IACjC,MAAM,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACzB,UAAU,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC7B,YAAY,EAAE,kBAAkB;IAChC,QAAQ,EAAE,uBAAuB;IACjC,KAAK,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACxB,MAAM,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACzB,OAAO,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1B,SAAS,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAChC,WAAW,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAClC,aAAa,EA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AW,EACT,qEAAqE;QACrE,+EAA+E;IACjF,WAAW,EAAE,OAAC,CAAC,MAAM,CAAC,EAAE,CAAC;IACzB,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,KAAK,EAAE;QAC7B,MAAM,MAAM,GAAG,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC;QAClE,OAAO,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC;IACrD,CAAC;CACF,CAAC;AAEF,iFAAiF;AAEjF,MAAM,UAAU,GAAsB;IACpC,IAAI,EAAE,QAAQ;IACd,WAAW,EAAE,mGAAmG;IAChH,WAAW,EAAE,OAAC,CAAC,MAAM,CAAC,EAAE,CAAC;IACzB,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE;QACpC,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,UAAU,EAAE,CAAC;QACxC,OAAO,EAAE,CAAC;YACR,MAAM,EAAE,IAAI;YACZ,iBAAiB,EAAE,MAAM,CAAC,MAAM;YAChC,WAAW,EAAE,KAAK,CAAC,MAAM;YACzB,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;SACpC,CAAC,CAAC;IACL,CAAC;CACF,CAAC;AAEF,iFAAiF;AAEpE,QAAA,SAAS,GAAwB;IAC5C,qBAAqB;IACrB,8BAA8B;IAC9B,mBAAmB;IACnB,aAAa;IACb,UAAU;CACX,CAAC"}
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ /**
3
+ * Transport helpers for @datacules/agent-identity-mcp.
4
+ *
5
+ * Provides two transports:
6
+ * - StdioServerTransport : stdin/stdout, for Claude Desktop / Claude Code / Cursor config
7
+ * - createHttpMcpTransport: HTTP + SSE, for hosted / networked deployments
8
+ *
9
+ * The HTTP transport adds optional bearer-token auth. The SSE endpoint at
10
+ * GET /sse initialises a session; the message endpoint at POST /messages
11
+ * receives client tool calls and posts responses back over the SSE stream.
12
+ */
13
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17
+ desc = { enumerable: true, get: function() { return m[k]; } };
18
+ }
19
+ Object.defineProperty(o, k2, desc);
20
+ }) : (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ }));
24
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
25
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
26
+ }) : function(o, v) {
27
+ o["default"] = v;
28
+ });
29
+ var __importStar = (this && this.__importStar) || (function () {
30
+ var ownKeys = function(o) {
31
+ ownKeys = Object.getOwnPropertyNames || function (o) {
32
+ var ar = [];
33
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
34
+ return ar;
35
+ };
36
+ return ownKeys(o);
37
+ };
38
+ return function (mod) {
39
+ if (mod && mod.__esModule) return mod;
40
+ var result = {};
41
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
42
+ __setModuleDefault(result, mod);
43
+ return result;
44
+ };
45
+ })();
46
+ Object.defineProperty(exports, "__esModule", { value: true });
47
+ exports.StdioServerTransport = void 0;
48
+ exports.startHttpMcpTransport = startHttpMcpTransport;
49
+ const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
50
+ Object.defineProperty(exports, "StdioServerTransport", { enumerable: true, get: function () { return stdio_js_1.StdioServerTransport; } });
51
+ const sse_js_1 = require("@modelcontextprotocol/sdk/server/sse.js");
52
+ /**
53
+ * Start an HTTP + SSE MCP transport.
54
+ *
55
+ * Session lifecycle:
56
+ * 1. Client opens GET /sse — transport creates an SSEServerTransport,
57
+ * connects it to the MCP Server, and starts streaming.
58
+ * 2. Client POSTs tool calls to POST /messages?sessionId=<id>.
59
+ * 3. Transport routes each message to the correct session and replies
60
+ * via the open SSE stream.
61
+ *
62
+ * Returns a cleanup function that closes the HTTP server.
63
+ */
64
+ async function startHttpMcpTransport(options) {
65
+ const { server, port = 3002, host = '127.0.0.1', authToken } = options;
66
+ // Session registry: sessionId → active SSEServerTransport
67
+ const sessions = new Map();
68
+ const http = await Promise.resolve().then(() => __importStar(require('node:http')));
69
+ function authenticate(req, res) {
70
+ if (!authToken)
71
+ return true;
72
+ const header = req.headers['authorization'] ?? '';
73
+ if (header === `Bearer ${authToken}`)
74
+ return true;
75
+ res.writeHead(401, { 'Content-Type': 'application/json' });
76
+ res.end(JSON.stringify({ error: 'Unauthorized — valid Bearer token required' }));
77
+ return false;
78
+ }
79
+ const httpServer = http.createServer(async (req, res) => {
80
+ const url = new URL(req.url ?? '/', `http://${host}:${port}`);
81
+ // CORS for browser-based MCP clients
82
+ res.setHeader('Access-Control-Allow-Origin', '*');
83
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
84
+ res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type');
85
+ if (req.method === 'OPTIONS') {
86
+ res.writeHead(204);
87
+ res.end();
88
+ return;
89
+ }
90
+ if (!authenticate(req, res))
91
+ return;
92
+ // ── SSE session init ──────────────────────────────────────────────────
93
+ if (req.method === 'GET' && url.pathname === '/sse') {
94
+ const transport = new sse_js_1.SSEServerTransport('/messages', res);
95
+ sessions.set(transport.sessionId, transport);
96
+ req.on('close', () => sessions.delete(transport.sessionId));
97
+ await server.connect(transport);
98
+ return;
99
+ }
100
+ // ── Incoming tool call message ────────────────────────────────────────
101
+ if (req.method === 'POST' && url.pathname === '/messages') {
102
+ const sessionId = url.searchParams.get('sessionId') ?? '';
103
+ const transport = sessions.get(sessionId);
104
+ if (!transport) {
105
+ res.writeHead(404, { 'Content-Type': 'application/json' });
106
+ res.end(JSON.stringify({ error: `Session ${sessionId} not found or expired` }));
107
+ return;
108
+ }
109
+ await transport.handlePostMessage(req, res);
110
+ return;
111
+ }
112
+ // ── Health probe (GET /) ──────────────────────────────────────────────
113
+ if (req.method === 'GET' && url.pathname === '/') {
114
+ res.writeHead(200, { 'Content-Type': 'application/json' });
115
+ res.end(JSON.stringify({ ok: true, sessions: sessions.size, transport: 'http+sse' }));
116
+ return;
117
+ }
118
+ res.writeHead(404);
119
+ res.end();
120
+ });
121
+ await new Promise((resolve) => httpServer.listen(port, host, resolve));
122
+ console.error(`[agent-identity-mcp] HTTP+SSE transport listening on http://${host}:${port}`);
123
+ return () => httpServer.close();
124
+ }
125
+ //# sourceMappingURL=transports.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transports.js","sourceRoot":"","sources":["../../src/transports.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCH,sDAoEC;AAzGD,wEAAiF;AAKxE,qGALA,+BAAoB,OAKA;AAJ7B,oEAA6E;AAwB7E;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,qBAAqB,CAAC,OAAgC;IAC1E,MAAM,EAAE,MAAM,EAAE,IAAI,GAAG,IAAI,EAAE,IAAI,GAAG,WAAW,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;IAEvE,0DAA0D;IAC1D,MAAM,QAAQ,GAAG,IAAI,GAAG,EAA8B,CAAC;IAEvD,MAAM,IAAI,GAAG,wDAAa,WAAW,GAAC,CAAC;IAEvC,SAAS,YAAY,CAAC,GAAoB,EAAE,GAAmB;QAC7D,IAAI,CAAC,SAAS;YAAE,OAAO,IAAI,CAAC;QAC5B,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,eAAe,CAAC,IAAI,EAAE,CAAC;QAClD,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AAG,EAAE,CAAC;IAChC,CAAC,CAAC,CAAC;IAEH,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;IAC7E,OAAO,CAAC,KAAK,CAAC,+DAA+D,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC;IAE7F,OAAO,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;AAClC,CAAC"}
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ /**
3
+ * MCP-specific type extensions for @datacules/agent-identity.
4
+ *
5
+ * McpRequestContext extends AgentRequestContext with the MCP session and
6
+ * client identifiers so audit logs can trace a credential resolution back
7
+ * to the exact MCP session that triggered it.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG"}