agentguardiam-node-sdk 0.0.0-stage → 0.2.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 CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # Node staging SDK
2
+
3
+ Build with `npm ci && npm run build`. Each task callback uses a scoped MCP credential, which is revoked when the callback completes. Every exchange is MCP: the agent key goes only to the task-token broker (`/gw/broker/mcp`) to mint, revoke and read approval status, and tool calls go to the gateway (`/gw/mcp`) with the task token.
4
+
5
+ ```ts
6
+ import { AgentGuard } from "./dist/index.js";
7
+
8
+ const gateway = new AgentGuard("http://localhost:8000", process.env.AGW_AGENT_KEY!);
9
+ const result = await gateway.task("Read staging customer", {
10
+ tools: ["crm_get_customer"],
11
+ tenantId: "ten_a",
12
+ }, (task) => task.call("crm_get_customer", { tenant_id: "ten_a", customer_id: "C-001" }));
13
+ ```
14
+
15
+ Pass both `userId` and the matching `userToken` to mint a task for a human principal. The dashboard token is sent only on the broker's mint call. A positive wait in seconds as the third argument to `task.call` waits for an existing human approval, subject to the task expiry, and retries the exact call once. `Held` exposes the approval ID and `Denied` exposes the decision code.
@@ -0,0 +1,32 @@
1
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
+ export declare class Denied extends Error {
3
+ readonly code: string;
4
+ readonly guard: string;
5
+ readonly reason: string;
6
+ readonly requestId: string;
7
+ constructor(code: string, guard: string, reason: string, requestId: string);
8
+ }
9
+ export declare class Held extends Error {
10
+ readonly code: string;
11
+ readonly approvalId: string;
12
+ readonly requestId: string;
13
+ constructor(code: string, approvalId: string, requestId: string);
14
+ }
15
+ export type TaskOptions = {
16
+ tools: string[];
17
+ userId?: string;
18
+ userToken?: string;
19
+ tenantId?: string;
20
+ ttlS?: number;
21
+ };
22
+ export declare class AgentGuard {
23
+ #private;
24
+ constructor(baseUrl: string, agentKey: string);
25
+ task<T>(purpose: string, options: TaskOptions, useTask: (task: Task) => Promise<T>): Promise<T>;
26
+ }
27
+ export declare class Task {
28
+ #private;
29
+ constructor(client: Client, baseUrl: string, agentHeaders: Record<string, string>, expiresAt: number);
30
+ listTools(): Promise<string[]>;
31
+ call(tool: string, parameters: Record<string, unknown>, waitForApprovalS?: number): Promise<unknown>;
32
+ }
package/dist/index.js ADDED
@@ -0,0 +1,216 @@
1
+ // AgentGuardIAM client: every exchange with AgentGuardIAM is MCP. The task-token broker
2
+ // (/gw/broker/mcp, agent key) mints, revokes and reports approvals; the gateway (/gw/mcp, task token) runs tools.
3
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
5
+ import { setTimeout } from "node:timers/promises";
6
+ const REQUESTED_TTL_CAP = 2 ** 31 - 1;
7
+ const APPROVAL_MARGIN_MS = 5_000;
8
+ const POLL_INTERVAL_MS = 2_000;
9
+ const REQUEST_TIMEOUT_MS = 10_000;
10
+ export class Denied extends Error {
11
+ code;
12
+ guard;
13
+ reason;
14
+ requestId;
15
+ constructor(code, guard, reason, requestId) {
16
+ super(`Gateway denied the request (${code})`);
17
+ this.code = code;
18
+ this.guard = guard;
19
+ this.reason = reason;
20
+ this.requestId = requestId;
21
+ }
22
+ }
23
+ export class Held extends Error {
24
+ code;
25
+ approvalId;
26
+ requestId;
27
+ constructor(code, approvalId, requestId) {
28
+ super(`Gateway paused the call (${code})`);
29
+ this.code = code;
30
+ this.approvalId = approvalId;
31
+ this.requestId = requestId;
32
+ }
33
+ }
34
+ export class AgentGuard {
35
+ #baseUrl;
36
+ #agentKey;
37
+ constructor(baseUrl, agentKey) {
38
+ this.#baseUrl = baseUrl.replace(/\/+$/, "");
39
+ this.#agentKey = agentKey;
40
+ }
41
+ async task(purpose, options, useTask) {
42
+ const agentHeaders = { "X-Agent-Key": this.#agentKey };
43
+ // The signed-in user's bearer is sent to the broker for human attribution only.
44
+ const mintHeaders = options.userToken === undefined
45
+ ? agentHeaders
46
+ : { ...agentHeaders, Authorization: `Bearer ${options.userToken}` };
47
+ const grant = await brokerCall(this.#baseUrl, mintHeaders, "issue_task_token", {
48
+ task_purpose: purpose,
49
+ requested_tools: options.tools,
50
+ user_id: options.userId ?? null,
51
+ tenant_id: options.tenantId ?? null,
52
+ ttl_s: options.ttlS ?? REQUESTED_TTL_CAP,
53
+ });
54
+ if (typeof grant.jti !== "string" || !grant.jti)
55
+ throw internalError("Invalid task grant");
56
+ const client = new Client({ name: "agentguardiam-node", version: "0.2.0" });
57
+ let taskFailed = false;
58
+ try {
59
+ const expiresAt = typeof grant.expires_at === "string" ? Date.parse(grant.expires_at) : NaN;
60
+ if (typeof grant.token !== "string" || !grant.token || !Number.isFinite(expiresAt)) {
61
+ throw internalError("Invalid task grant");
62
+ }
63
+ await client.connect(new StreamableHTTPClientTransport(new URL(`${this.#baseUrl}/gw/mcp`), {
64
+ requestInit: { headers: { Authorization: `Bearer ${grant.token}` }, redirect: "error" },
65
+ }));
66
+ return await useTask(new Task(client, this.#baseUrl, agentHeaders, expiresAt));
67
+ }
68
+ catch (error) {
69
+ taskFailed = true;
70
+ throw error;
71
+ }
72
+ finally {
73
+ let teardownError;
74
+ try {
75
+ await client.close();
76
+ }
77
+ catch (error) {
78
+ teardownError = error;
79
+ }
80
+ try {
81
+ await brokerCall(this.#baseUrl, agentHeaders, "revoke_task_token", { jti: grant.jti });
82
+ }
83
+ catch (error) {
84
+ teardownError ??= error;
85
+ }
86
+ if (!taskFailed && teardownError !== undefined)
87
+ throw teardownError;
88
+ }
89
+ }
90
+ }
91
+ export class Task {
92
+ #client;
93
+ #baseUrl;
94
+ #agentHeaders;
95
+ #expiresAt;
96
+ constructor(client, baseUrl, agentHeaders, expiresAt) {
97
+ this.#client = client;
98
+ this.#baseUrl = baseUrl;
99
+ this.#agentHeaders = agentHeaders;
100
+ this.#expiresAt = expiresAt;
101
+ }
102
+ async listTools() {
103
+ const names = [];
104
+ const seen = new Set();
105
+ let cursor;
106
+ do {
107
+ const result = await this.#client.listTools(cursor === undefined ? undefined : { cursor });
108
+ names.push(...result.tools.map(({ name }) => name));
109
+ cursor = result.nextCursor;
110
+ if (cursor !== undefined) {
111
+ if (seen.has(cursor))
112
+ throw internalError("Gateway repeated a tool listing cursor");
113
+ seen.add(cursor);
114
+ }
115
+ } while (cursor !== undefined);
116
+ return names;
117
+ }
118
+ async call(tool, parameters, waitForApprovalS = 0) {
119
+ if (!Number.isFinite(waitForApprovalS) || waitForApprovalS < 0)
120
+ throw new RangeError("Invalid approval wait");
121
+ const replay = structuredClone(parameters);
122
+ try {
123
+ return await this.#call(tool, structuredClone(replay));
124
+ }
125
+ catch (error) {
126
+ if (!(error instanceof Held) || waitForApprovalS === 0)
127
+ throw error;
128
+ await this.#waitForApproval(error, waitForApprovalS);
129
+ }
130
+ return this.#call(tool, replay);
131
+ }
132
+ async #call(tool, args) {
133
+ const result = await this.#client.callTool({ name: tool, arguments: args });
134
+ const parts = Array.isArray(result.content) ? result.content : [];
135
+ if (result.isError === true)
136
+ throw toolError(parts);
137
+ if (result.structuredContent !== undefined)
138
+ return result.structuredContent;
139
+ const single = parts[0];
140
+ return parts.length === 1 && isRecord(single) && typeof single.text === "string" ? single.text : parts;
141
+ }
142
+ async #waitForApproval(hold, seconds) {
143
+ const budget = Math.min(seconds * 1_000, this.#expiresAt - Date.now() - APPROVAL_MARGIN_MS);
144
+ const deadline = performance.now() + budget;
145
+ while (performance.now() < deadline) {
146
+ let review;
147
+ try {
148
+ review = await brokerCall(this.#baseUrl, this.#agentHeaders, "get_approval_status", { approval_id: hold.approvalId }, Math.max(1, Math.ceil(deadline - performance.now())));
149
+ }
150
+ catch (error) {
151
+ if (performance.now() >= deadline)
152
+ break;
153
+ throw error;
154
+ }
155
+ if (review.status === "approved")
156
+ return;
157
+ if (review.status === "rejected")
158
+ throw new Denied("approval_rejected", "approvals", "Approval was rejected", hold.requestId);
159
+ if (review.status === "expired" || review.status === "consumed")
160
+ break;
161
+ if (review.status !== "pending")
162
+ throw internalError("Unknown approval status");
163
+ const remaining = deadline - performance.now();
164
+ if (remaining <= 0)
165
+ break;
166
+ await setTimeout(Math.min(POLL_INTERVAL_MS, remaining));
167
+ }
168
+ throw new Denied("approval_expired", "approvals", "Approval wait expired", hold.requestId);
169
+ }
170
+ }
171
+ /** Calls one task-token broker tool over MCP with the agent key (and, when minting, the user bearer). */
172
+ async function brokerCall(baseUrl, headers, tool, args, timeoutMs = REQUEST_TIMEOUT_MS) {
173
+ const client = new Client({ name: "agentguardiam-node", version: "0.2.0" });
174
+ await client.connect(new StreamableHTTPClientTransport(new URL(`${baseUrl}/gw/broker/mcp`), { requestInit: { headers, redirect: "error" } }), { timeout: timeoutMs });
175
+ try {
176
+ const result = await client.callTool({ name: tool, arguments: args }, undefined, { timeout: timeoutMs });
177
+ const parts = Array.isArray(result.content) ? result.content : [];
178
+ if (result.isError === true)
179
+ throw toolError(parts);
180
+ if (!isRecord(result.structuredContent))
181
+ throw internalError("Invalid broker response");
182
+ return result.structuredContent;
183
+ }
184
+ finally {
185
+ await client.close();
186
+ }
187
+ }
188
+ function isRecord(value) {
189
+ return value !== null && typeof value === "object" && !Array.isArray(value);
190
+ }
191
+ function internalError(reason) {
192
+ return new Denied("internal_error", "gateway", reason, "");
193
+ }
194
+ function toolError(parts) {
195
+ for (const part of parts) {
196
+ if (!isRecord(part) || typeof part.text !== "string")
197
+ continue;
198
+ let body;
199
+ try {
200
+ body = JSON.parse(part.text);
201
+ }
202
+ catch {
203
+ continue;
204
+ }
205
+ const detail = isRecord(body) && isRecord(body.agw) ? body.agw : null;
206
+ if (!detail || typeof detail.code !== "string" || typeof detail.request_id !== "string")
207
+ continue;
208
+ if (detail.action === "hold" && typeof detail.approval_id === "string") {
209
+ return new Held(detail.code, detail.approval_id, detail.request_id);
210
+ }
211
+ if (detail.action === "deny") {
212
+ return new Denied(detail.code, typeof detail.guard === "string" ? detail.guard : "gateway", typeof detail.reason === "string" ? detail.reason : "Tool call denied", detail.request_id);
213
+ }
214
+ }
215
+ return new Denied("downstream_error", "gateway", "Tool call failed", "");
216
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
- {
2
- "name": "agentguardiam-node-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
1
+ {
2
+ "name": "agentguardiam-node-sdk",
3
+ "version": "0.2.0",
4
+ "description": "Node.js SDK for AgentGuard MCP Gateway",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsc",
20
+ "test": "npm run build && node --test",
21
+ "prepublishOnly": "npm run test"
22
+ },
23
+ "keywords": [
24
+ "mcp",
25
+ "agentguard",
26
+ "ai-agent",
27
+ "security",
28
+ "gateway"
29
+ ],
30
+ "author": "Than Duc Trung, email: thanductrung123@gmail.com",
31
+ "license": "MIT",
32
+ "dependencies": {
33
+ "@modelcontextprotocol/sdk": "1.32.2"
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": "^22.0.0",
37
+ "typescript": "^5.9.0"
38
+ }
6
39
  }