agentguardiam-node-sdk 0.0.0-stage → 0.2.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/README.md +32 -3
- package/dist/index.d.ts +46 -0
- package/dist/index.js +258 -0
- package/package.json +38 -5
package/README.md
CHANGED
|
@@ -1,3 +1,32 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
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.
|
|
16
|
+
|
|
17
|
+
To pause for a human approval across requests, keep the grant (0.2.1+) and resume with the same arguments:
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
const grant = await gateway.acquireTask("Refund order 5521", { tools: ["payments_transfer"], userId, userToken });
|
|
21
|
+
try {
|
|
22
|
+
await grant.session((task) => task.call("payments_transfer", args));
|
|
23
|
+
} catch (error) {
|
|
24
|
+
if (!(error instanceof Held)) throw error;
|
|
25
|
+
// ... later, when grant.approvalStatus(error.approvalId) is "approved":
|
|
26
|
+
await grant.session((task) => task.call("payments_transfer", args));
|
|
27
|
+
} finally {
|
|
28
|
+
await grant.revoke();
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
A private CA is added with `NODE_EXTRA_CA_CERTS=<ca.pem>`, which extends Node's trust store.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
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
|
+
* Mint a grant that outlives one callback: keep it across a pause for human approval, then call
|
|
28
|
+
* `grant.session(...)` again with the SAME arguments and finally `grant.revoke()` (parity with the Python SDK).
|
|
29
|
+
*/
|
|
30
|
+
acquireTask(purpose: string, options: TaskOptions): Promise<TaskGrant>;
|
|
31
|
+
}
|
|
32
|
+
/** A task credential whose sessions share one task identity. */
|
|
33
|
+
export declare class TaskGrant {
|
|
34
|
+
#private;
|
|
35
|
+
readonly expiresAt: number;
|
|
36
|
+
constructor(baseUrl: string, agentHeaders: Record<string, string>, jti: string, token: string, expiresAt: number);
|
|
37
|
+
session<T>(useTask: (task: Task) => Promise<T>): Promise<T>;
|
|
38
|
+
approvalStatus(approvalId: string): Promise<string | null>;
|
|
39
|
+
revoke(): Promise<void>;
|
|
40
|
+
}
|
|
41
|
+
export declare class Task {
|
|
42
|
+
#private;
|
|
43
|
+
constructor(client: Client, baseUrl: string, agentHeaders: Record<string, string>, expiresAt: number);
|
|
44
|
+
listTools(): Promise<string[]>;
|
|
45
|
+
call(tool: string, parameters: Record<string, unknown>, waitForApprovalS?: number): Promise<unknown>;
|
|
46
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
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
|
+
const SDK_VERSION = "0.2.1";
|
|
11
|
+
export class Denied extends Error {
|
|
12
|
+
code;
|
|
13
|
+
guard;
|
|
14
|
+
reason;
|
|
15
|
+
requestId;
|
|
16
|
+
constructor(code, guard, reason, requestId) {
|
|
17
|
+
super(`Gateway denied the request (${code})`);
|
|
18
|
+
this.code = code;
|
|
19
|
+
this.guard = guard;
|
|
20
|
+
this.reason = reason;
|
|
21
|
+
this.requestId = requestId;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export class Held extends Error {
|
|
25
|
+
code;
|
|
26
|
+
approvalId;
|
|
27
|
+
requestId;
|
|
28
|
+
constructor(code, approvalId, requestId) {
|
|
29
|
+
super(`Gateway paused the call (${code})`);
|
|
30
|
+
this.code = code;
|
|
31
|
+
this.approvalId = approvalId;
|
|
32
|
+
this.requestId = requestId;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export class AgentGuard {
|
|
36
|
+
#baseUrl;
|
|
37
|
+
#agentKey;
|
|
38
|
+
constructor(baseUrl, agentKey) {
|
|
39
|
+
this.#baseUrl = baseUrl.replace(/\/+$/, "");
|
|
40
|
+
this.#agentKey = agentKey;
|
|
41
|
+
}
|
|
42
|
+
async task(purpose, options, useTask) {
|
|
43
|
+
const grant = await this.acquireTask(purpose, options);
|
|
44
|
+
let taskFailed = false;
|
|
45
|
+
try {
|
|
46
|
+
return await grant.session(useTask);
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
taskFailed = true;
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
try {
|
|
54
|
+
await grant.revoke();
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
if (!taskFailed)
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Mint a grant that outlives one callback: keep it across a pause for human approval, then call
|
|
64
|
+
* `grant.session(...)` again with the SAME arguments and finally `grant.revoke()` (parity with the Python SDK).
|
|
65
|
+
*/
|
|
66
|
+
async acquireTask(purpose, options) {
|
|
67
|
+
const agentHeaders = { "X-Agent-Key": this.#agentKey };
|
|
68
|
+
// The signed-in user's bearer is sent to the broker for human attribution only.
|
|
69
|
+
const mintHeaders = options.userToken === undefined
|
|
70
|
+
? agentHeaders
|
|
71
|
+
: { ...agentHeaders, Authorization: `Bearer ${options.userToken}` };
|
|
72
|
+
const grant = await brokerCall(this.#baseUrl, mintHeaders, "issue_task_token", {
|
|
73
|
+
task_purpose: purpose,
|
|
74
|
+
requested_tools: options.tools,
|
|
75
|
+
user_id: options.userId ?? null,
|
|
76
|
+
tenant_id: options.tenantId ?? null,
|
|
77
|
+
ttl_s: options.ttlS ?? REQUESTED_TTL_CAP,
|
|
78
|
+
});
|
|
79
|
+
if (typeof grant.jti !== "string" || !grant.jti)
|
|
80
|
+
throw internalError("Invalid task grant");
|
|
81
|
+
const expiresAt = typeof grant.expires_at === "string" ? Date.parse(grant.expires_at) : NaN;
|
|
82
|
+
if (typeof grant.token !== "string" || !grant.token || !Number.isFinite(expiresAt)) {
|
|
83
|
+
try {
|
|
84
|
+
await brokerCall(this.#baseUrl, agentHeaders, "revoke_task_token", { jti: grant.jti });
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
// the grant is unusable either way
|
|
88
|
+
}
|
|
89
|
+
throw internalError("Invalid task grant");
|
|
90
|
+
}
|
|
91
|
+
return new TaskGrant(this.#baseUrl, agentHeaders, grant.jti, grant.token, expiresAt);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/** A task credential whose sessions share one task identity. */
|
|
95
|
+
export class TaskGrant {
|
|
96
|
+
#baseUrl;
|
|
97
|
+
#agentHeaders;
|
|
98
|
+
#jti;
|
|
99
|
+
#token;
|
|
100
|
+
expiresAt;
|
|
101
|
+
constructor(baseUrl, agentHeaders, jti, token, expiresAt) {
|
|
102
|
+
this.#baseUrl = baseUrl;
|
|
103
|
+
this.#agentHeaders = agentHeaders;
|
|
104
|
+
this.#jti = jti;
|
|
105
|
+
this.#token = token;
|
|
106
|
+
this.expiresAt = expiresAt;
|
|
107
|
+
}
|
|
108
|
+
async session(useTask) {
|
|
109
|
+
if (!this.#token)
|
|
110
|
+
throw new Denied("token_revoked", "token_broker", "Task grant was revoked", "");
|
|
111
|
+
const client = new Client({ name: "agentguardiam-node", version: SDK_VERSION });
|
|
112
|
+
try {
|
|
113
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(`${this.#baseUrl}/gw/mcp`), {
|
|
114
|
+
requestInit: { headers: { Authorization: `Bearer ${this.#token}` }, redirect: "error" },
|
|
115
|
+
}));
|
|
116
|
+
return await useTask(new Task(client, this.#baseUrl, this.#agentHeaders, this.expiresAt));
|
|
117
|
+
}
|
|
118
|
+
finally {
|
|
119
|
+
await client.close();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
async approvalStatus(approvalId) {
|
|
123
|
+
const review = await brokerCall(this.#baseUrl, this.#agentHeaders, "get_approval_status", { approval_id: approvalId });
|
|
124
|
+
return typeof review.status === "string" ? review.status : null;
|
|
125
|
+
}
|
|
126
|
+
async revoke() {
|
|
127
|
+
if (!this.#token)
|
|
128
|
+
return;
|
|
129
|
+
this.#token = "";
|
|
130
|
+
await brokerCall(this.#baseUrl, this.#agentHeaders, "revoke_task_token", { jti: this.#jti });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
export class Task {
|
|
134
|
+
#client;
|
|
135
|
+
#baseUrl;
|
|
136
|
+
#agentHeaders;
|
|
137
|
+
#expiresAt;
|
|
138
|
+
constructor(client, baseUrl, agentHeaders, expiresAt) {
|
|
139
|
+
this.#client = client;
|
|
140
|
+
this.#baseUrl = baseUrl;
|
|
141
|
+
this.#agentHeaders = agentHeaders;
|
|
142
|
+
this.#expiresAt = expiresAt;
|
|
143
|
+
}
|
|
144
|
+
async listTools() {
|
|
145
|
+
const names = [];
|
|
146
|
+
const seen = new Set();
|
|
147
|
+
let cursor;
|
|
148
|
+
do {
|
|
149
|
+
const result = await this.#client.listTools(cursor === undefined ? undefined : { cursor });
|
|
150
|
+
names.push(...result.tools.map(({ name }) => name));
|
|
151
|
+
cursor = result.nextCursor;
|
|
152
|
+
if (cursor !== undefined) {
|
|
153
|
+
if (seen.has(cursor))
|
|
154
|
+
throw internalError("Gateway repeated a tool listing cursor");
|
|
155
|
+
seen.add(cursor);
|
|
156
|
+
}
|
|
157
|
+
} while (cursor !== undefined);
|
|
158
|
+
return names;
|
|
159
|
+
}
|
|
160
|
+
async call(tool, parameters, waitForApprovalS = 0) {
|
|
161
|
+
if (!Number.isFinite(waitForApprovalS) || waitForApprovalS < 0)
|
|
162
|
+
throw new RangeError("Invalid approval wait");
|
|
163
|
+
const replay = structuredClone(parameters);
|
|
164
|
+
try {
|
|
165
|
+
return await this.#call(tool, structuredClone(replay));
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
if (!(error instanceof Held) || waitForApprovalS === 0)
|
|
169
|
+
throw error;
|
|
170
|
+
await this.#waitForApproval(error, waitForApprovalS);
|
|
171
|
+
}
|
|
172
|
+
return this.#call(tool, replay);
|
|
173
|
+
}
|
|
174
|
+
async #call(tool, args) {
|
|
175
|
+
const result = await this.#client.callTool({ name: tool, arguments: args });
|
|
176
|
+
const parts = Array.isArray(result.content) ? result.content : [];
|
|
177
|
+
if (result.isError === true)
|
|
178
|
+
throw toolError(parts);
|
|
179
|
+
if (result.structuredContent !== undefined)
|
|
180
|
+
return result.structuredContent;
|
|
181
|
+
const single = parts[0];
|
|
182
|
+
return parts.length === 1 && isRecord(single) && typeof single.text === "string" ? single.text : parts;
|
|
183
|
+
}
|
|
184
|
+
async #waitForApproval(hold, seconds) {
|
|
185
|
+
const budget = Math.min(seconds * 1_000, this.#expiresAt - Date.now() - APPROVAL_MARGIN_MS);
|
|
186
|
+
const deadline = performance.now() + budget;
|
|
187
|
+
while (performance.now() < deadline) {
|
|
188
|
+
let review;
|
|
189
|
+
try {
|
|
190
|
+
review = await brokerCall(this.#baseUrl, this.#agentHeaders, "get_approval_status", { approval_id: hold.approvalId }, Math.max(1, Math.ceil(deadline - performance.now())));
|
|
191
|
+
}
|
|
192
|
+
catch (error) {
|
|
193
|
+
if (performance.now() >= deadline)
|
|
194
|
+
break;
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
if (review.status === "approved")
|
|
198
|
+
return;
|
|
199
|
+
if (review.status === "rejected")
|
|
200
|
+
throw new Denied("approval_rejected", "approvals", "Approval was rejected", hold.requestId);
|
|
201
|
+
if (review.status === "expired" || review.status === "consumed")
|
|
202
|
+
break;
|
|
203
|
+
if (review.status !== "pending")
|
|
204
|
+
throw internalError("Unknown approval status");
|
|
205
|
+
const remaining = deadline - performance.now();
|
|
206
|
+
if (remaining <= 0)
|
|
207
|
+
break;
|
|
208
|
+
await setTimeout(Math.min(POLL_INTERVAL_MS, remaining));
|
|
209
|
+
}
|
|
210
|
+
throw new Denied("approval_expired", "approvals", "Approval wait expired", hold.requestId);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
/** Calls one task-token broker tool over MCP with the agent key (and, when minting, the user bearer). */
|
|
214
|
+
async function brokerCall(baseUrl, headers, tool, args, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
215
|
+
const client = new Client({ name: "agentguardiam-node", version: SDK_VERSION });
|
|
216
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(`${baseUrl}/gw/broker/mcp`), { requestInit: { headers, redirect: "error" } }), { timeout: timeoutMs });
|
|
217
|
+
try {
|
|
218
|
+
const result = await client.callTool({ name: tool, arguments: args }, undefined, { timeout: timeoutMs });
|
|
219
|
+
const parts = Array.isArray(result.content) ? result.content : [];
|
|
220
|
+
if (result.isError === true)
|
|
221
|
+
throw toolError(parts);
|
|
222
|
+
if (!isRecord(result.structuredContent))
|
|
223
|
+
throw internalError("Invalid broker response");
|
|
224
|
+
return result.structuredContent;
|
|
225
|
+
}
|
|
226
|
+
finally {
|
|
227
|
+
await client.close();
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
function isRecord(value) {
|
|
231
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
232
|
+
}
|
|
233
|
+
function internalError(reason) {
|
|
234
|
+
return new Denied("internal_error", "gateway", reason, "");
|
|
235
|
+
}
|
|
236
|
+
function toolError(parts) {
|
|
237
|
+
for (const part of parts) {
|
|
238
|
+
if (!isRecord(part) || typeof part.text !== "string")
|
|
239
|
+
continue;
|
|
240
|
+
let body;
|
|
241
|
+
try {
|
|
242
|
+
body = JSON.parse(part.text);
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
const detail = isRecord(body) && isRecord(body.agw) ? body.agw : null;
|
|
248
|
+
if (!detail || typeof detail.code !== "string" || typeof detail.request_id !== "string")
|
|
249
|
+
continue;
|
|
250
|
+
if (detail.action === "hold" && typeof detail.approval_id === "string") {
|
|
251
|
+
return new Held(detail.code, detail.approval_id, detail.request_id);
|
|
252
|
+
}
|
|
253
|
+
if (detail.action === "deny") {
|
|
254
|
+
return new Denied(detail.code, typeof detail.guard === "string" ? detail.guard : "gateway", typeof detail.reason === "string" ? detail.reason : "Tool call denied", detail.request_id);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return new Denied("downstream_error", "gateway", "Tool call failed", "");
|
|
258
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "agentguardiam-node-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
1
|
+
{
|
|
2
|
+
"name": "agentguardiam-node-sdk",
|
|
3
|
+
"version": "0.2.1",
|
|
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
|
}
|