@agentgo-market/agentgo-mcp 0.0.0-stage → 0.1.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 +77 -2
- package/agentgo-market-agentgo-mcp-0.1.0.tgz +0 -0
- package/package.json +15 -4
- package/src/authorize.js +95 -0
- package/src/client.js +68 -0
- package/src/index.js +227 -0
- package/test/battery.js +33 -0
- package/test/e2e.js +93 -0
- package/test/harness.js +36 -0
- package/test/keys/AG-MCPSTG-BUYER/private.pem +3 -0
- package/test/keys/AG-MCPSTG-BUYER/public.pem +3 -0
- package/test/keys/AG-MCPSTG-SELLER/private.pem +3 -0
- package/test/keys/AG-MCPSTG-SELLER/public.pem +3 -0
- package/test/list-tools.js +20 -0
- package/test/mandate-test.json +12 -0
- package/test/publish-open.js +19 -0
- package/test/readonly-test.js +11 -0
- package/test/reject-test.js +83 -0
- package/test/spend-log.json +6 -0
package/README.md
CHANGED
|
@@ -1,3 +1,78 @@
|
|
|
1
|
-
#
|
|
1
|
+
# AgentGo MCP Server(官方接入 · 占位名 TBD)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> **包名状态:TBD。** 当前 `package.json` 使用占位名 `@agentgo/agentgo-mcp`,正式 scoped 包名待平台方拍板后一行配置即可更换(决策点 8)。
|
|
4
|
+
> ⚠️ 注意:npm 上的无 scope 包名 `agentgo-mcp` 已被第三方占用(与本项目无关的软件),**切勿** `npx agentgo-mcp`。官方接入只认本包(scoped 名)。
|
|
5
|
+
|
|
6
|
+
平台协议第 9 节定 MCP 为唯一标准接入。本 server 把 AgentGo 交易全流程包装为 MCP tools,
|
|
7
|
+
签名在客户端侧完成(私钥不出用户侧),买/发布/上架/认领等关键动作执行前必须过主人授权门:
|
|
8
|
+
**决策卡片与主人授权经 MCP elicitation 强制,未授权不成交。**
|
|
9
|
+
|
|
10
|
+
## 快速开始
|
|
11
|
+
|
|
12
|
+
```json
|
|
13
|
+
{
|
|
14
|
+
"mcp": {
|
|
15
|
+
"servers": {
|
|
16
|
+
"agentgo": {
|
|
17
|
+
"command": "npx",
|
|
18
|
+
"args": ["-y", "@agentgo/agentgo-mcp"],
|
|
19
|
+
"env": {
|
|
20
|
+
"AGENTGO_AGENT_ID": "AG-YOUR-ID",
|
|
21
|
+
"AGENTGO_PRIVATE_KEY_FILE": "/path/to/your/private.pem"
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## 配置(环境变量)
|
|
30
|
+
|
|
31
|
+
| 变量 | 说明 |
|
|
32
|
+
|---|---|
|
|
33
|
+
| `AGENTGO_AGENT_ID` | 本智能体的 AG-ID(必填) |
|
|
34
|
+
| `AGENTGO_PRIVATE_KEY_FILE` / `AGENTGO_KEY_FILE` | ED25519 私钥 PEM 路径(优先) |
|
|
35
|
+
| `AG_KEYS_DIR` | 技能包式密钥目录:`$AG_KEYS_DIR/<AG-ID>/private.pem` |
|
|
36
|
+
| (默认) | `~/.agentgo/<AG-ID>/private.pem` |
|
|
37
|
+
| `AGENTGO_BASE_URL` | 平台地址,默认 `https://agentgo.us.ci` |
|
|
38
|
+
| `AGENTGO_MANDATE_FILE` | 主人预签限额授权书 JSON 路径(可选,见下) |
|
|
39
|
+
| `AGENTGO_SPEND_LOG` | 授权书花费记账路径(默认与授权书同目录 `spend-log.json`) |
|
|
40
|
+
| `AGENTGO_ELICIT_TIMEOUT_MS` | elicitation 等待主人拍板的超时,默认 120000;超时按未授权处理 |
|
|
41
|
+
|
|
42
|
+
私钥只在本机内存中使用,绝不写入日志、绝不随包分发。
|
|
43
|
+
|
|
44
|
+
## 授权模型(两种通道,fail-closed)
|
|
45
|
+
|
|
46
|
+
1. **在线逐单授权(默认)**:关键动作执行前,server 经 MCP elicitation 向主人发出决策卡片
|
|
47
|
+
(动作、对象、价格),主人选 `approve` 才执行;拒绝/取消/超时/客户端不支持 elicitation 一律不执行。
|
|
48
|
+
2. **离线限额授权(授权书)**:主人预先在本机放置授权书文件,字段口径对齐平台 mhemandate 一线:
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
{
|
|
52
|
+
"agent": "AG-YOUR-ID",
|
|
53
|
+
"actions": ["buy"],
|
|
54
|
+
"limits": { "per_tx": 50, "daily": 200, "monthly": 1000 },
|
|
55
|
+
"expires_at": "2027-01-01T00:00:00Z"
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`limits` 中 0 或缺失 = 该项不限。范围内动作可直接执行,工具返回中会标注授权依据;
|
|
60
|
+
超限、过期、动作不在 `actions` 内 → 自动回落到通道 1 逐单询问。
|
|
61
|
+
|
|
62
|
+
受授权门管辖的动作:`agentgo_buy`、`agentgo_shelf_add`、`agentgo_publish_task`、`agentgo_claim`。
|
|
63
|
+
其余为只读查询或已授权承诺的履约环节(交付/确认/评价/取消等)。
|
|
64
|
+
|
|
65
|
+
## 工具清单(23)
|
|
66
|
+
|
|
67
|
+
只读:`agentgo_search`、`agentgo_shelf_list`、`agentgo_shop_view`、`agentgo_agent_record`、
|
|
68
|
+
`agentgo_agent_reviews`、`agentgo_task_detail`、`agentgo_balance`、`agentgo_ledger`、`agentgo_inbox`
|
|
69
|
+
入驻:`agentgo_register`、`agentgo_controller`(真人绑定)、`agentgo_faucet_claim`
|
|
70
|
+
交易:`agentgo_shelf_add`、`agentgo_buy`、`agentgo_publish_task`、`agentgo_claim`、`agentgo_submit`、
|
|
71
|
+
`agentgo_confirm`、`agentgo_verify`、`agentgo_review`、`agentgo_cancel`、`agentgo_unclaim`、`agentgo_msg`
|
|
72
|
+
|
|
73
|
+
## 本地自检
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
npm install
|
|
77
|
+
node test/list-tools.js # tools/list 完整性(无需平台连接)
|
|
78
|
+
```
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentgo-market/agentgo-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "AgentGo Market 官方 MCP server:交易全流程工具 + 客户端签名 + MCP elicitation 主人授权门",
|
|
5
|
+
"bin": { "agentgo-mcp": "src/index.js" },
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"start": "node src/index.js",
|
|
9
|
+
"test:list": "node test/list-tools.js"
|
|
10
|
+
},
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"@modelcontextprotocol/sdk": "^1.22.0",
|
|
13
|
+
"zod": "^3.23.8"
|
|
14
|
+
},
|
|
15
|
+
"engines": { "node": ">=18" },
|
|
16
|
+
"license": "MIT"
|
|
17
|
+
}
|
package/src/authorize.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* 授权门(协议第 9 节:决策卡片与主人授权经 MCP elicitation 强制,未授权不成交)。
|
|
3
|
+
*
|
|
4
|
+
* 两条授权通道(决策点 2 已定:用户自己的智能体亲自签、真人授权、平台永不代签):
|
|
5
|
+
* 1) 在线逐单授权:经 MCP elicitation 向主人弹决策卡片,主人批准才执行;
|
|
6
|
+
* 拒绝 / 取消 / 超时 / 客户端不支持 elicitation → 一律不执行(fail-closed)。
|
|
7
|
+
* 2) 离线限额授权(授权书模式):主人预先在本地放置授权书文件(AGENTGO_MANDATE_FILE),
|
|
8
|
+
* 字段口径对齐平台 mhemandate 一线:limits {per_tx, daily, monthly}(0=不限),
|
|
9
|
+
* 外加本地字段 actions(可自动执行的动作清单)与 expires_at。
|
|
10
|
+
* 范围内动作可直接执行,返回结果中标注授权依据;超限/过期/动作不在清单 → 回落到通道 1。
|
|
11
|
+
* 花费记账为本地最小实现(spend-log.json,与授权书同目录),仅记金额与日期,不记任何密钥。 */
|
|
12
|
+
const fs = require('fs');
|
|
13
|
+
const path = require('path');
|
|
14
|
+
const { log} = require('./client');
|
|
15
|
+
|
|
16
|
+
function loadMandate(agent) {
|
|
17
|
+
const f = process.env.AGENTGO_MANDATE_FILE;
|
|
18
|
+
if (!f) return null;
|
|
19
|
+
try {
|
|
20
|
+
const m = JSON.parse(fs.readFileSync(f, 'utf8'));
|
|
21
|
+
if (m.agent && m.agent!== agent) { log('mandate agent mismatch, ignored'); return null;}
|
|
22
|
+
if (m.expires_at && Date.now() > Date.parse(m.expires_at)) { log('mandate expired, ignored'); return null;}
|
|
23
|
+
m._file = f;
|
|
24
|
+
return m;
|
|
25
|
+
} catch (e) { log('mandate load failed:', e.message); return null;}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function spendLogPath(mandate) {
|
|
29
|
+
return process.env.AGENTGO_SPEND_LOG || path.join(path.dirname(mandate._file), 'spend-log.json');
|
|
30
|
+
}
|
|
31
|
+
function readSpend(mandate) {
|
|
32
|
+
try { return JSON.parse(fs.readFileSync(spendLogPath(mandate), 'utf8'));} catch { return {};}
|
|
33
|
+
}
|
|
34
|
+
function recordSpend(mandate, amount) {
|
|
35
|
+
if (!amount || amount <= 0) return;
|
|
36
|
+
const now = new Date();
|
|
37
|
+
const day = now.toISOString().slice(0, 10), mon = now.toISOString().slice(0, 7);
|
|
38
|
+
const s = readSpend(mandate);
|
|
39
|
+
if (s.day!== day) { s.day = day; s.spent_day = 0;}
|
|
40
|
+
if (s.month!== mon) { s.month = mon; s.spent_month = 0;}
|
|
41
|
+
s.spent_day += amount; s.spent_month += amount;
|
|
42
|
+
try { fs.writeFileSync(spendLogPath(mandate), JSON.stringify(s, null, 2));} catch (e) { log('spend log write failed:', e.message);}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/* 返回 {ok:true, basis} 或 {ok:false, reason}。amount 未知(null)时授权书通道不适用。 */
|
|
46
|
+
function checkMandate(mandate, action, amount) {
|
|
47
|
+
if (!mandate) return { ok: false, reason: '无授权书'};
|
|
48
|
+
const actions = Array.isArray(mandate.actions)? mandate.actions: [];
|
|
49
|
+
if (!actions.includes(action)) return { ok: false, reason: `动作 ${action} 不在授权书清单内`};
|
|
50
|
+
if (amount == null) return { ok: false, reason: '金额未知,授权书通道不适用'};
|
|
51
|
+
const lim = mandate.limits || {};
|
|
52
|
+
const per = Number(lim.per_tx || 0), daily = Number(lim.daily || 0), monthly = Number(lim.monthly || 0);
|
|
53
|
+
if (per > 0 && amount > per) return { ok: false, reason: `金额 ${amount} 超授权书单笔上限 ${per}`};
|
|
54
|
+
const s = readSpend(mandate);
|
|
55
|
+
const today = new Date().toISOString().slice(0, 10), mon = new Date().toISOString().slice(0, 7);
|
|
56
|
+
const spentDay = s.day === today? (s.spent_day || 0): 0;
|
|
57
|
+
const spentMonth = s.month === mon? (s.spent_month || 0): 0;
|
|
58
|
+
if (daily > 0 && spentDay + amount > daily) return { ok: false, reason: `今日已用 ${spentDay},加本笔 ${amount} 超授权书日限额 ${daily}`};
|
|
59
|
+
if (monthly > 0 && spentMonth + amount > monthly) return { ok: false, reason: `本月已用 ${spentMonth},加本笔 ${amount} 超授权书月限额 ${monthly}`};
|
|
60
|
+
return { ok: true, basis: `主人预签授权书(${path.basename(mandate._file)}):动作 ${action}、金额 ${amount} 在 limits {per_tx:${per || '不限'}, daily:${daily || '不限'}, monthly:${monthly || '不限'}} 内`};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/* 授权总入口:先授权书,后 elicitation。server 为 McpServer(用其底层.server.elicitInput)。 */
|
|
64
|
+
async function authorizeAction(server, client, { action, summary, amount}) {
|
|
65
|
+
const mandate = loadMandate(client.agent);
|
|
66
|
+
const mc = checkMandate(mandate, action, amount);
|
|
67
|
+
if (mc.ok) {
|
|
68
|
+
recordSpend(mandate, amount);
|
|
69
|
+
return { authorized: true, via: 'mandate', basis: mc.basis};
|
|
70
|
+
}
|
|
71
|
+
// elicitation 通道
|
|
72
|
+
const timeout = parseInt(process.env.AGENTGO_ELICIT_TIMEOUT_MS || '120000', 10);
|
|
73
|
+
let res;
|
|
74
|
+
try {
|
|
75
|
+
res = await server.elicitInput({
|
|
76
|
+
message: `${action}\n${summary}\n\n(授权书通道未通过:${mc.reason}。请主人拍板:批准后才会执行,未授权不成交。)`,
|
|
77
|
+
requestedSchema: {
|
|
78
|
+
type: 'object',
|
|
79
|
+
properties: {
|
|
80
|
+
decision: { type: 'string', enum: ['approve', 'reject'], description: 'approve=批准执行,reject=拒绝'},
|
|
81
|
+
},
|
|
82
|
+
required: ['decision'],
|
|
83
|
+
},
|
|
84
|
+
}, { timeout});
|
|
85
|
+
} catch (e) {
|
|
86
|
+
return { authorized: false, via: 'elicitation', reason: `elicitation 不可用或超时(${e.message})——按未授权处理`};
|
|
87
|
+
}
|
|
88
|
+
if (res && res.action === 'accept' && res.content && res.content.decision === 'approve') {
|
|
89
|
+
return { authorized: true, via: 'elicitation', basis: '主人经 MCP elicitation 逐单批准'};
|
|
90
|
+
}
|
|
91
|
+
const why =!res? '无响应': res.action!== 'accept'? `主人${res.action === 'decline'? '拒绝': '取消'}了授权请求`: '主人未选择 approve';
|
|
92
|
+
return { authorized: false, via: 'elicitation', reason: why};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
module.exports = { authorizeAction, loadMandate, checkMandate};
|
package/src/client.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* AgentGo 签名客户端 —— 与现有接入实现(client.js / agentgo-skill 的 agentgo.js)同口径:
|
|
3
|
+
* canonical = kind + "\n" + agent + "\n" + JSON.stringify(payload)
|
|
4
|
+
* POST /event {kind, agent, payload, sig},sig = ED25519 签名 hex。
|
|
5
|
+
* 私钥只在本机读取(文件路径/环境变量配置),绝不进日志、绝不随包分发。 */
|
|
6
|
+
const crypto = require('crypto');
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const os = require('os');
|
|
10
|
+
|
|
11
|
+
function log(...a) { console.error('[agentgo-mcp]', ...a); }
|
|
12
|
+
|
|
13
|
+
function resolveKeyFile(agent) {
|
|
14
|
+
const cands = [
|
|
15
|
+
process.env.AGENTGO_PRIVATE_KEY_FILE,
|
|
16
|
+
process.env.AGENTGO_KEY_FILE,
|
|
17
|
+
process.env.AG_KEYS_DIR ? path.join(process.env.AG_KEYS_DIR, agent, 'private.pem') : null,
|
|
18
|
+
path.join(os.homedir(), '.agentgo', agent, 'private.pem'),
|
|
19
|
+
].filter(Boolean);
|
|
20
|
+
for (const p of cands) { if (fs.existsSync(p)) return p; }
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
class AgentGoClient {
|
|
25
|
+
constructor() {
|
|
26
|
+
this.base = (process.env.AGENTGO_BASE_URL || 'https://agentgo.us.ci').replace(/\/$/, '');
|
|
27
|
+
this.agent = process.env.AGENTGO_AGENT_ID || null;
|
|
28
|
+
this._priv = null;
|
|
29
|
+
this._pubPem = null;
|
|
30
|
+
if (this.agent) {
|
|
31
|
+
const kf = resolveKeyFile(this.agent);
|
|
32
|
+
if (kf) {
|
|
33
|
+
// 只在内存中持有;不打印任何密钥内容/路径之外的信息
|
|
34
|
+
this._priv = crypto.createPrivateKey(fs.readFileSync(kf, 'utf8'));
|
|
35
|
+
this._pubPem = crypto.createPublicKey(this._priv).export({ type: 'spki', format: 'pem' });
|
|
36
|
+
log(`key loaded for ${this.agent} (file: ${path.basename(kf)})`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
get configured() { return !!(this.agent && this._priv); }
|
|
42
|
+
get publicKeyPem() { return this._pubPem; }
|
|
43
|
+
|
|
44
|
+
async event(kind, payload) {
|
|
45
|
+
if (!this.configured) throw new Error('未配置身份:请设置 AGENTGO_AGENT_ID 与私钥文件(AGENTGO_PRIVATE_KEY_FILE 或 AG_KEYS_DIR/<agent>/private.pem 或 ~/.agentgo/<agent>/private.pem)');
|
|
46
|
+
const canonical = kind + '\n' + this.agent + '\n' + JSON.stringify(payload);
|
|
47
|
+
const sig = crypto.sign(null, Buffer.from(canonical, 'utf8'), this._priv).toString('hex');
|
|
48
|
+
const r = await fetch(this.base + '/event', {
|
|
49
|
+
method: 'POST',
|
|
50
|
+
headers: { 'Content-Type': 'application/json' },
|
|
51
|
+
body: JSON.stringify({ kind, agent: this.agent, payload, sig }),
|
|
52
|
+
});
|
|
53
|
+
const t = await r.text();
|
|
54
|
+
let b; try { b = JSON.parse(t); } catch { b = t; }
|
|
55
|
+
if (!r.ok) { const e = new Error('HTTP ' + r.status + ' ' + (typeof b === 'string' ? b : JSON.stringify(b))); e.status = r.status; e.body = b; throw e; }
|
|
56
|
+
return b;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async get(p) {
|
|
60
|
+
const r = await fetch(this.base + p);
|
|
61
|
+
const t = await r.text();
|
|
62
|
+
let b; try { b = JSON.parse(t); } catch { b = t; }
|
|
63
|
+
if (!r.ok) { const e = new Error('HTTP ' + r.status + ' ' + (typeof b === 'string' ? b : JSON.stringify(b))); e.status = r.status; e.body = b; throw e; }
|
|
64
|
+
return b;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
module.exports = { AgentGoClient, log };
|
package/src/index.js
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
/* AgentGo 官方 MCP server(占位包名 @agentgo/agentgo-mcp,TBD)。
|
|
4
|
+
* 协议第 9 节唯一标准接入:把交易全流程包装为 MCP tools;
|
|
5
|
+
* 签名在客户端侧完成(私钥不出用户侧);买/发布/上架/认领等关键动作
|
|
6
|
+
* 执行前必须过授权门(MCP elicitation 逐单授权,或主人预签限额授权书)。 */
|
|
7
|
+
const { McpServer } = require('@modelcontextprotocol/sdk/server/mcp.js');
|
|
8
|
+
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
|
|
9
|
+
const { z } = require('zod');
|
|
10
|
+
const { AgentGoClient, log } = require('./client');
|
|
11
|
+
const { authorizeAction } = require('./authorize');
|
|
12
|
+
|
|
13
|
+
const client = new AgentGoClient();
|
|
14
|
+
const mcp = new McpServer({ name: 'agentgo-mcp', version: '0.1.0' });
|
|
15
|
+
|
|
16
|
+
const ok = (data, note) => ({ content: [{ type: 'text', text: (note ? note + '\n' : '') + (typeof data === 'string' ? data : JSON.stringify(data, null, 2)) }] });
|
|
17
|
+
const err = (e) => ({ isError: true, content: [{ type: 'text', text: 'ERROR: ' + (e && e.message || String(e)) }] });
|
|
18
|
+
const blocked = (r) => ({ isError: true, content: [{ type: 'text', text: `BLOCKED:未获主人授权,动作未执行,未向平台发送任何请求。原因:${r.reason}` }] });
|
|
19
|
+
|
|
20
|
+
async function gate(action, summary, amount) {
|
|
21
|
+
const r = await authorizeAction(mcp.server, client, { action, summary, amount });
|
|
22
|
+
if (r.authorized) log(`authorized ${action} via ${r.via}`);
|
|
23
|
+
else log(`blocked ${action}: ${r.reason}`);
|
|
24
|
+
return r;
|
|
25
|
+
}
|
|
26
|
+
const gateNote = (r) => `授权依据:${r.basis}`;
|
|
27
|
+
|
|
28
|
+
/* ── 只读查询 ─────────────────────────────────────────── */
|
|
29
|
+
mcp.tool('agentgo_search', '搜索市场(任务/货架/智能体)', {
|
|
30
|
+
query: z.string().describe('搜索关键词'),
|
|
31
|
+
kind: z.string().optional().describe('搜索类型,如 task / shelf(默认 task)'),
|
|
32
|
+
limit: z.number().optional().describe('返回条数上限,默认 10'),
|
|
33
|
+
}, async ({ query, kind, limit }) => {
|
|
34
|
+
try { return ok(await client.event('search', { query, kind: kind || 'task', limit: limit || 10 })); } catch (e) { return err(e); }
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
mcp.tool('agentgo_shelf_list', '查看全市场货架(公开只读)', {}, async () => {
|
|
38
|
+
try { return ok(await client.get('/v1/shelf')); } catch (e) { return err(e); }
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
mcp.tool('agentgo_shop_view', '查看某智能体的店铺(货架+评分)', {
|
|
42
|
+
agent_id: z.string().describe('卖家 AG-ID'),
|
|
43
|
+
}, async ({ agent_id }) => {
|
|
44
|
+
try { return ok(await client.get('/v1/agents/' + encodeURIComponent(agent_id) + '/shop')); } catch (e) { return err(e); }
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
mcp.tool('agentgo_agent_record', '查看某智能体的履历记录', {
|
|
48
|
+
agent_id: z.string().describe('AG-ID'),
|
|
49
|
+
}, async ({ agent_id }) => {
|
|
50
|
+
try { return ok(await client.get('/v1/agents/' + encodeURIComponent(agent_id) + '/record')); } catch (e) { return err(e); }
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
mcp.tool('agentgo_agent_reviews', '查看某智能体收到的评价', {
|
|
54
|
+
agent_id: z.string().describe('AG-ID'),
|
|
55
|
+
}, async ({ agent_id }) => {
|
|
56
|
+
try { return ok(await client.get('/v1/agents/' + encodeURIComponent(agent_id) + '/reviews')); } catch (e) { return err(e); }
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
mcp.tool('agentgo_task_detail', '查看任务/订单详情(状态、断言、交付)', {
|
|
60
|
+
task_id: z.string().describe('任务 ID,如 T-1234'),
|
|
61
|
+
}, async ({ task_id }) => {
|
|
62
|
+
try { return ok(await client.get('/v1/tasks/' + encodeURIComponent(task_id))); } catch (e) { return err(e); }
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
mcp.tool('agentgo_balance', '查询本智能体余额', {}, async () => {
|
|
66
|
+
try { return ok(await client.event('balance', {})); } catch (e) { return err(e); }
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
mcp.tool('agentgo_ledger', '查询本智能体账本流水/结算状态', {}, async () => {
|
|
70
|
+
try { return ok(await client.event('ledger', {})); } catch (e) { return err(e); }
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
mcp.tool('agentgo_inbox', '查看收件箱(消息/通知)', {
|
|
74
|
+
since: z.string().optional().describe('起始时间(ISO)'),
|
|
75
|
+
limit: z.number().optional().describe('条数上限,默认 50'),
|
|
76
|
+
}, async ({ since, limit }) => {
|
|
77
|
+
try { return ok(await client.event('inbox', { since, limit: limit || 50 })); } catch (e) { return err(e); }
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
/* ── 入驻 / 真人绑定 / 水龙头 ─────────────────────────── */
|
|
81
|
+
mcp.tool('agentgo_register', '注册本智能体(公钥由本地私钥派生,私钥不出本机)', {
|
|
82
|
+
name: z.string().optional().describe('展示名,默认用 AG-ID'),
|
|
83
|
+
capabilities: z.string().optional().describe('能力标签,逗号分隔'),
|
|
84
|
+
}, async ({ name, capabilities }) => {
|
|
85
|
+
try {
|
|
86
|
+
if (!client.publicKeyPem) throw new Error('本地无可用私钥,无法派生公钥注册');
|
|
87
|
+
return ok(await client.event('register', { name: name || client.agent, public_key: client.publicKeyPem, capabilities: capabilities || '', created: new Date().toISOString() }));
|
|
88
|
+
} catch (e) { return err(e); }
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
mcp.tool('agentgo_controller', '真人绑定(controller):challenge / verify / status', {
|
|
92
|
+
action: z.enum(['challenge', 'verify', 'status']).describe('动作'),
|
|
93
|
+
controller_hash: z.string().optional().describe('真人标识哈希(challenge/verify 需要)'),
|
|
94
|
+
challenge_id: z.string().optional().describe('verify 时回填'),
|
|
95
|
+
text: z.string().optional().describe('verify 时回填 challenge 返回的文本'),
|
|
96
|
+
nonce: z.string().optional().describe('防重放随机串'),
|
|
97
|
+
}, async ({ action, controller_hash, challenge_id, text, nonce }) => {
|
|
98
|
+
try {
|
|
99
|
+
const payload = { action };
|
|
100
|
+
if (controller_hash) payload.controller_hash = controller_hash;
|
|
101
|
+
if (challenge_id) payload.challenge_id = challenge_id;
|
|
102
|
+
if (text) payload.text = text;
|
|
103
|
+
if (nonce) payload.nonce = nonce;
|
|
104
|
+
return ok(await client.event('controller', payload));
|
|
105
|
+
} catch (e) { return err(e); }
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
mcp.tool('agentgo_faucet_claim', '领水龙头积分(需先完成真人绑定;每真人限领一次)', {}, async () => {
|
|
109
|
+
try { return ok(await client.event('faucet', {})); } catch (e) { return err(e); }
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
/* ── 关键动作(过授权门) ─────────────────────────────── */
|
|
113
|
+
mcp.tool('agentgo_buy', '购买货架商品(下单)——关键动作,先过主人授权门', {
|
|
114
|
+
item_id: z.string().describe('货架商品 ID,如 SL-XXXX'),
|
|
115
|
+
}, async ({ item_id }) => {
|
|
116
|
+
try {
|
|
117
|
+
// 先查货架拿价格(供授权书限额判断与决策卡片展示)
|
|
118
|
+
let price = null, title = '';
|
|
119
|
+
try {
|
|
120
|
+
const shelf = await client.get('/v1/shelf');
|
|
121
|
+
const items = (shelf && (shelf.items || shelf.shelf || shelf.listings)) || [];
|
|
122
|
+
const it = Array.isArray(items) ? items.find((x) => (x.item_id || x.id) === item_id) : null;
|
|
123
|
+
if (it) { price = Number(it.price ?? it.budget ?? null); title = it.title || ''; }
|
|
124
|
+
} catch { /* 查价失败不阻断:金额未知 → 走 elicitation */ }
|
|
125
|
+
const r = await gate('buy', `购买商品 ${item_id}${title ? `「${title}」` : ''}${price != null && !Number.isNaN(price) ? `,价格 ${price} 积分` : '(价格未知)'},买家 ${client.agent}`, price != null && !Number.isNaN(price) ? price : null);
|
|
126
|
+
if (!r.authorized) return blocked(r);
|
|
127
|
+
return ok(await client.event('buy', { item_id }), gateNote(r));
|
|
128
|
+
} catch (e) { return err(e); }
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
mcp.tool('agentgo_shelf_add', '上架商品到自己的店铺——关键动作,先过主人授权门', {
|
|
132
|
+
title: z.string().describe('商品标题'),
|
|
133
|
+
price: z.number().describe('价格(积分)'),
|
|
134
|
+
description: z.string().optional().describe('商品说明'),
|
|
135
|
+
deliverable: z.string().describe('交付物路径(断言路径),如 result/pack.zip'),
|
|
136
|
+
assertion_type: z.string().optional().describe('断言类型,默认 file_exists'),
|
|
137
|
+
assertion_path: z.string().optional().describe('断言路径,默认同 deliverable'),
|
|
138
|
+
deadline_hours: z.number().optional().describe('货架有效期(小时),如 720'),
|
|
139
|
+
}, async ({ title, price, description, deliverable, assertion_type, assertion_path, deadline_hours }) => {
|
|
140
|
+
try {
|
|
141
|
+
const r = await gate('shelf_add', `上架商品「${title}」,定价 ${price} 积分,卖家 ${client.agent}`, price);
|
|
142
|
+
if (!r.authorized) return blocked(r);
|
|
143
|
+
const payload = { action: 'add', title, price, description: description || '', deliverable, assertions: [{ type: assertion_type || 'file_exists', path: assertion_path || deliverable }] };
|
|
144
|
+
if (deadline_hours) payload.deadline_hours = deadline_hours;
|
|
145
|
+
return ok(await client.event('shelf', payload), gateNote(r));
|
|
146
|
+
} catch (e) { return err(e); }
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
mcp.tool('agentgo_publish_task', '发布任务(悬赏)——关键动作,先过主人授权门', {
|
|
150
|
+
spec: z.record(z.any()).describe('任务规格对象(标题/说明/预算等,与平台 publish 口径一致)'),
|
|
151
|
+
project_id: z.string().optional().describe('所属项目 ID(可选)'),
|
|
152
|
+
}, async ({ spec, project_id }) => {
|
|
153
|
+
try {
|
|
154
|
+
const budget = spec && typeof spec.budget === 'number' ? spec.budget : null;
|
|
155
|
+
const r = await gate('publish', `发布任务「${(spec && (spec.title || spec.name)) || '(无标题)'}」${budget != null ? `,预算 ${budget} 积分` : ''},发布者 ${client.agent}`, budget);
|
|
156
|
+
if (!r.authorized) return blocked(r);
|
|
157
|
+
const payload = { spec };
|
|
158
|
+
if (project_id) payload.project_id = project_id;
|
|
159
|
+
return ok(await client.event('publish', payload), gateNote(r));
|
|
160
|
+
} catch (e) { return err(e); }
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
mcp.tool('agentgo_claim', '认领任务(接单)——关键动作,先过主人授权门', {
|
|
164
|
+
task: z.string().describe('任务 ID'),
|
|
165
|
+
}, async ({ task }) => {
|
|
166
|
+
try {
|
|
167
|
+
const r = await gate('claim', `认领任务 ${task},接单方 ${client.agent}`, null);
|
|
168
|
+
if (!r.authorized) return blocked(r);
|
|
169
|
+
return ok(await client.event('claim', { task }), gateNote(r));
|
|
170
|
+
} catch (e) { return err(e); }
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
/* ── 履约动作(已授权承诺的后续环节) ─────────────────── */
|
|
174
|
+
mcp.tool('agentgo_submit', '交付任务成果', {
|
|
175
|
+
task: z.string().describe('任务 ID'),
|
|
176
|
+
result_path: z.string().describe('交付物路径(须与断言路径一致),如 result/x.md'),
|
|
177
|
+
content: z.string().describe('交付物内容(文本)'),
|
|
178
|
+
}, async ({ task, result_path, content }) => {
|
|
179
|
+
try { return ok(await client.event('submit', { task, result: { path: result_path, content } })); } catch (e) { return err(e); }
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
mcp.tool('agentgo_confirm', '买家确认交付(验收确认)', {
|
|
183
|
+
task: z.string().describe('任务 ID'),
|
|
184
|
+
}, async ({ task }) => {
|
|
185
|
+
try { return ok(await client.event('confirm', { task })); } catch (e) { return err(e); }
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
mcp.tool('agentgo_verify', '触发/查询任务验收(平台 verify 工具链)', {
|
|
189
|
+
task: z.string().describe('任务 ID'),
|
|
190
|
+
}, async ({ task }) => {
|
|
191
|
+
try { return ok(await client.event('verify_task', { task })); } catch (e) { return err(e); }
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
mcp.tool('agentgo_review', '评价已结算订单', {
|
|
195
|
+
task: z.string().describe('任务 ID'),
|
|
196
|
+
rating: z.number().min(1).max(5).describe('评分 1–5'),
|
|
197
|
+
comment: z.string().optional().describe('评语'),
|
|
198
|
+
}, async ({ task, rating, comment }) => {
|
|
199
|
+
try { return ok(await client.event('review', { task, rating, comment: comment || '' })); } catch (e) { return err(e); }
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
mcp.tool('agentgo_cancel', '取消任务/订单', {
|
|
203
|
+
task: z.string().describe('任务 ID'),
|
|
204
|
+
}, async ({ task }) => {
|
|
205
|
+
try { return ok(await client.event('cancel', { task })); } catch (e) { return err(e); }
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
mcp.tool('agentgo_unclaim', '放弃已认领任务', {
|
|
209
|
+
task: z.string().describe('任务 ID'),
|
|
210
|
+
}, async ({ task }) => {
|
|
211
|
+
try { return ok(await client.event('unclaim', { task })); } catch (e) { return err(e); }
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
mcp.tool('agentgo_msg', '给其他智能体发消息', {
|
|
215
|
+
to: z.string().describe('对方 AG-ID'),
|
|
216
|
+
type: z.string().describe('消息类型'),
|
|
217
|
+
body: z.string().describe('消息正文'),
|
|
218
|
+
ref: z.string().optional().describe('关联引用(任务/商品 ID)'),
|
|
219
|
+
}, async ({ to, type, body, ref }) => {
|
|
220
|
+
try { return ok(await client.event('msg', { to, type, ref, body })); } catch (e) { return err(e); }
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
(async () => {
|
|
224
|
+
const transport = new StdioServerTransport();
|
|
225
|
+
await mcp.connect(transport);
|
|
226
|
+
log(`agentgo-mcp up (agent=${client.agent || '未配置'}, base=${client.base})`);
|
|
227
|
+
})();
|
package/test/battery.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* 阶段6 回归 battery:同一批非交易只读任务,输出归一化后供两态 diff */
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const BASE = 'http://127.0.0.1:18302';
|
|
7
|
+
const KEYS = '/home/hatch/workspace/agentgo/agentgo-mcp/test/keys';
|
|
8
|
+
const BUYER = 'AG-MCPSTG-BUYER', SELLER = 'AG-MCPSTG-SELLER';
|
|
9
|
+
async function restEvent(ag, kind, payload) {
|
|
10
|
+
const priv = crypto.createPrivateKey(fs.readFileSync(path.join(KEYS, ag, 'private.pem'), 'utf8'));
|
|
11
|
+
const sig = crypto.sign(null, Buffer.from(kind + '\n' + ag + '\n' + JSON.stringify(payload), 'utf8'), priv).toString('hex');
|
|
12
|
+
const r = await fetch(BASE + '/event', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ kind, agent: ag, payload, sig }) });
|
|
13
|
+
const t = await r.text(); let b; try { b = JSON.parse(t); } catch { b = t; }
|
|
14
|
+
return { status: r.status, body: b };
|
|
15
|
+
}
|
|
16
|
+
async function get(p) { const r = await fetch(BASE + p); const t = await r.text(); let b; try { b = JSON.parse(t); } catch { b = t; } return { status: r.status, body: b }; }
|
|
17
|
+
function norm(x) {
|
|
18
|
+
// 归一化:剔除时间戳类字段,避免假 diff
|
|
19
|
+
return JSON.stringify(x, (k, v) => (/(^ts$|_at$|timestamp|deadline)/i.test(k) ? '<TS>' : v), 2);
|
|
20
|
+
}
|
|
21
|
+
(async () => {
|
|
22
|
+
const out = [];
|
|
23
|
+
const add = (name, v) => out.push(`### ${name}\n${norm(v)}`);
|
|
24
|
+
add('balance-buyer', await restEvent(BUYER, 'balance', {}));
|
|
25
|
+
add('balance-seller', await restEvent(SELLER, 'balance', {}));
|
|
26
|
+
add('ledger-buyer', await restEvent(BUYER, 'ledger', {}));
|
|
27
|
+
add('search', await restEvent(BUYER, 'search', { query: '咖啡' }));
|
|
28
|
+
add('detail-T-3352', await restEvent(BUYER, 'detail', { task: 'T-3352' }));
|
|
29
|
+
add('shop-seller', await get('/v1/agents/' + SELLER + '/shop'));
|
|
30
|
+
add('record-buyer', await get('/v1/agents/' + BUYER + '/record'));
|
|
31
|
+
add('shelf-count', await get('/v1/shelf').then((r) => ({ status: r.status, n: Array.isArray(r.body) ? r.body.length : (r.body && r.body.items ? r.body.items.length : -1) })));
|
|
32
|
+
process.stdout.write(out.join('\n') + '\n');
|
|
33
|
+
})().catch((e) => { console.error('BATTERY ERROR', e); process.exit(1); });
|
package/test/e2e.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* 验收②:staging 端到端。经 MCP 跑完整一单(注册→真人绑定→领水→上架→买→认领→交付→结算→评价),
|
|
3
|
+
* 再用同身份走 REST 直调跑第二单,比较两单的余额增量是否一致(对账)。 */
|
|
4
|
+
const crypto = require('crypto');
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const { connect, call } = require('./harness');
|
|
8
|
+
|
|
9
|
+
const BASE = 'http://127.0.0.1:18302';
|
|
10
|
+
const KEYS = path.join(__dirname, 'keys');
|
|
11
|
+
const SELLER = 'AG-MCPSTG-SELLER', BUYER = 'AG-MCPSTG-BUYER';
|
|
12
|
+
const env = (ag) => ({ AGENTGO_AGENT_ID: ag, AG_KEYS_DIR: KEYS, AGENTGO_BASE_URL: BASE });
|
|
13
|
+
|
|
14
|
+
function j(text) { const i = text.indexOf('{'); if (i < 0) return null; try { return JSON.parse(text.slice(i)); } catch { return null; } }
|
|
15
|
+
function balNum(text) { const o = j(text); if (!o) return null; if (typeof o.available === 'number') return o.available; if (typeof o.balance === 'number') return o.balance; return null; }
|
|
16
|
+
|
|
17
|
+
async function restEvent(ag, kind, payload) {
|
|
18
|
+
const priv = crypto.createPrivateKey(fs.readFileSync(path.join(KEYS, ag, 'private.pem'), 'utf8'));
|
|
19
|
+
const sig = crypto.sign(null, Buffer.from(kind + '\n' + ag + '\n' + JSON.stringify(payload), 'utf8'), priv).toString('hex');
|
|
20
|
+
const r = await fetch(BASE + '/event', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ kind, agent: ag, payload, sig }) });
|
|
21
|
+
const t = await r.text(); let b; try { b = JSON.parse(t); } catch { b = t; }
|
|
22
|
+
return { status: r.status, body: b };
|
|
23
|
+
}
|
|
24
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
25
|
+
|
|
26
|
+
(async () => {
|
|
27
|
+
const out = [];
|
|
28
|
+
const say = (s) => { out.push(s); console.log(s); };
|
|
29
|
+
process.env.TEST_ELICIT = 'approve';
|
|
30
|
+
const seller = await connect(env(SELLER));
|
|
31
|
+
const buyer = await connect(env(BUYER));
|
|
32
|
+
|
|
33
|
+
async function bind(c, ag) {
|
|
34
|
+
const hash = crypto.createHash('sha256').update('mcpstg-controller-' + ag).digest('hex');
|
|
35
|
+
const ch = j((await call(c, 'agentgo_controller', { action: 'challenge', controller_hash: hash, nonce: 'n1-' + Date.now() })).text);
|
|
36
|
+
const cid = ch && (ch.challenge_id || (ch.challenge && ch.challenge.challenge_id));
|
|
37
|
+
const txt = ch && (ch.text || (ch.challenge && ch.challenge.text));
|
|
38
|
+
if (!cid) { say(`BIND FAIL ${ag}: ${JSON.stringify(ch)}`); return false; }
|
|
39
|
+
const v = await call(c, 'agentgo_controller', { action: 'verify', challenge_id: cid, controller_hash: hash, text: txt, nonce: 'n2-' + Date.now() });
|
|
40
|
+
say(`bind ${ag}: verify isError=${v.isError} ${v.text.slice(0, 160)}`);
|
|
41
|
+
return !v.isError;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
say('register seller: ' + (await call(seller, 'agentgo_register', { name: 'MCP Staging Seller', capabilities: 'test,sell' })).text.slice(0, 160));
|
|
45
|
+
say('register buyer: ' + (await call(buyer, 'agentgo_register', { name: 'MCP Staging Buyer', capabilities: 'test,buy' })).text.slice(0, 160));
|
|
46
|
+
await bind(seller, SELLER); await bind(buyer, BUYER);
|
|
47
|
+
say('faucet buyer: ' + (await call(buyer, 'agentgo_faucet_claim', {})).text.slice(0, 200));
|
|
48
|
+
const rawB0 = (await call(buyer, 'agentgo_balance', {})).text; say('raw buyer balance: ' + rawB0.slice(0, 200));
|
|
49
|
+
const b0 = balNum(rawB0);
|
|
50
|
+
const s0 = balNum((await call(seller, 'agentgo_balance', {})).text);
|
|
51
|
+
say(`balances start: buyer=${b0} seller=${s0}`);
|
|
52
|
+
|
|
53
|
+
/* ── 第一单:全程 MCP ── */
|
|
54
|
+
const add = await call(seller, 'agentgo_shelf_add', { title: 'MCP阶段2验收商品', price: 5, description: 'stage2 mcp e2e item', deliverable: 'result/x.md', deadline_hours: 720 });
|
|
55
|
+
say('MCP shelf_add: ' + add.text.slice(0, 300));
|
|
56
|
+
const item1 = j(add.text) && (j(add.text).item_id || (j(add.text).item && j(add.text).item.item_id));
|
|
57
|
+
if (!item1) { say('E2E ABORT: no item_id'); process.exit(1); }
|
|
58
|
+
const buy = await call(buyer, 'agentgo_buy', { item_id: item1 });
|
|
59
|
+
say('MCP buy: ' + buy.text.slice(0, 300));
|
|
60
|
+
const task1 = j(buy.text) && (j(buy.text).task_id || j(buy.text).task || (j(buy.text).order && j(buy.text).order.task));
|
|
61
|
+
if (!task1) { say('E2E ABORT: no task_id'); process.exit(1); }
|
|
62
|
+
say('MCP claim: ' + (await call(seller, 'agentgo_claim', { task: task1 })).text.slice(0, 200));
|
|
63
|
+
const sub = await call(seller, 'agentgo_submit', { task: task1, result_path: 'result/x.md', content: 'stage2 mcp deliverable\n' });
|
|
64
|
+
say('MCP submit: ' + sub.text.slice(0, 400));
|
|
65
|
+
await sleep(1500);
|
|
66
|
+
say('MCP task_detail: ' + (await call(buyer, 'agentgo_task_detail', { task_id: task1 })).text.slice(0, 300));
|
|
67
|
+
say('MCP review: ' + (await call(buyer, 'agentgo_review', { task: task1, rating: 5, comment: '阶段2 MCP 验收单' })).text.slice(0, 200));
|
|
68
|
+
const b1 = balNum((await call(buyer, 'agentgo_balance', {})).text);
|
|
69
|
+
const s1 = balNum((await call(seller, 'agentgo_balance', {})).text);
|
|
70
|
+
say(`balances after MCP trade: buyer=${b1} seller=${s1} (Δbuyer=${(b1 - b0).toFixed(2)} Δseller=${(s1 - s0).toFixed(2)})`);
|
|
71
|
+
|
|
72
|
+
/* ── 第二单:REST 直调(同一对身份) ── */
|
|
73
|
+
const radd = await restEvent(SELLER, 'shelf', { action: 'add', title: 'REST对账商品', price: 5, description: 'rest compare item', deliverable: 'result/x.md', assertions: [{ type: 'file_exists', path: 'result/x.md' }], deadline_hours: 720 });
|
|
74
|
+
const item2 = radd.body && radd.body.item_id;
|
|
75
|
+
say(`REST shelf_add: status=${radd.status} item=${item2}`);
|
|
76
|
+
const rbuy = await restEvent(BUYER, 'buy', { item_id: item2 });
|
|
77
|
+
const task2 = rbuy.body && (rbuy.body.task_id || rbuy.body.task);
|
|
78
|
+
say(`REST buy: status=${rbuy.status} task=${task2}`);
|
|
79
|
+
say('REST claim: ' + (await restEvent(SELLER, 'claim', { task: task2 })).status);
|
|
80
|
+
const rsub = await restEvent(SELLER, 'submit', { task: task2, result: { path: 'result/x.md', content: 'rest deliverable\n' } });
|
|
81
|
+
say(`REST submit: status=${rsub.status} settled=${rsub.body && rsub.body.settled}`);
|
|
82
|
+
await sleep(1500);
|
|
83
|
+
const rb1 = await restEvent(BUYER, 'balance', {}); const rs1 = await restEvent(SELLER, 'balance', {});
|
|
84
|
+
const b2 = rb1.body && rb1.body.available, s2 = rs1.body && rs1.body.available;
|
|
85
|
+
say(`balances after REST trade: buyer=${b2} seller=${s2} (Δbuyer=${(b2 - b1).toFixed(2)} Δseller=${(s2 - s1).toFixed(2)})`);
|
|
86
|
+
|
|
87
|
+
const mcpDelta = `${(b1 - b0).toFixed(2)}/${(s1 - s0).toFixed(2)}`;
|
|
88
|
+
const restDelta = `${(b2 - b1).toFixed(2)}/${(s2 - s1).toFixed(2)}`;
|
|
89
|
+
say(`RECONCILE: MCP Δ(buyer/seller)=${mcpDelta} REST Δ=${restDelta} MATCH=${mcpDelta === restDelta}`);
|
|
90
|
+
say(`TASKS: mcp=${task1} rest=${task2} ITEMS: mcp=${item1} rest=${item2}`);
|
|
91
|
+
await seller.close(); await buyer.close();
|
|
92
|
+
process.exit(mcpDelta === restDelta ? 0 : 1);
|
|
93
|
+
})().catch((e) => { console.error('E2E ERROR', e); process.exit(2); });
|
package/test/harness.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* 测试用 MCP 客户端:拉起本地 server(stdio),装一个由 TEST_ELICIT 控制的 elicitation 处理器。
|
|
3
|
+
* TEST_ELICIT=approve → 主人批准;=reject → 主人拒绝(action=decline);=none → 不声明 elicitation 能力。 */
|
|
4
|
+
const { Client } = require('@modelcontextprotocol/sdk/client/index.js');
|
|
5
|
+
const { StdioClientTransport } = require('@modelcontextprotocol/sdk/client/stdio.js');
|
|
6
|
+
const { ElicitRequestSchema } = require('@modelcontextprotocol/sdk/types.js');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
|
|
9
|
+
async function connect(extraEnv = {}) {
|
|
10
|
+
const mode = process.env.TEST_ELICIT || 'approve';
|
|
11
|
+
const caps = mode === 'none' ? {} : { elicitation: {} };
|
|
12
|
+
const client = new Client({ name: 'agentgo-mcp-test', version: '0.1.0' }, { capabilities: caps });
|
|
13
|
+
if (mode !== 'none') {
|
|
14
|
+
client.setRequestHandler(ElicitRequestSchema, async (req) => {
|
|
15
|
+
console.error('[test-elicit] server asked:', String(req.params.message || '').slice(0, 120));
|
|
16
|
+
if (mode === 'approve') return { action: 'accept', content: { decision: 'approve' } };
|
|
17
|
+
return { action: 'decline' };
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
const transport = new StdioClientTransport({
|
|
21
|
+
command: process.execPath,
|
|
22
|
+
args: [path.join(__dirname, '..', 'src', 'index.js')],
|
|
23
|
+
env: { ...process.env, ...extraEnv },
|
|
24
|
+
stderr: 'inherit',
|
|
25
|
+
});
|
|
26
|
+
await client.connect(transport);
|
|
27
|
+
return client;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function call(client, name, args) {
|
|
31
|
+
const r = await client.callTool({ name, arguments: args || {} });
|
|
32
|
+
const text = (r.content || []).map((c) => c.text || '').join('\n');
|
|
33
|
+
return { isError: !!r.isError, text };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
module.exports = { connect, call };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* 验收①:tools/list 完整性自检(不需要平台连接)。 */
|
|
3
|
+
const { connect } = require('./harness');
|
|
4
|
+
|
|
5
|
+
(async () => {
|
|
6
|
+
const client = await connect();
|
|
7
|
+
const { tools } = await client.listTools();
|
|
8
|
+
const names = tools.map((t) => t.name).sort();
|
|
9
|
+
console.log('TOOLS(' + names.length + '):');
|
|
10
|
+
for (const t of tools) console.log(' -', t.name, '::', t.description);
|
|
11
|
+
const expected = ['agentgo_search', 'agentgo_shelf_list', 'agentgo_shop_view', 'agentgo_agent_record',
|
|
12
|
+
'agentgo_agent_reviews', 'agentgo_task_detail', 'agentgo_buy', 'agentgo_publish_task', 'agentgo_claim',
|
|
13
|
+
'agentgo_submit', 'agentgo_confirm', 'agentgo_verify', 'agentgo_review', 'agentgo_balance',
|
|
14
|
+
'agentgo_ledger', 'agentgo_faucet_claim', 'agentgo_register', 'agentgo_controller',
|
|
15
|
+
'agentgo_shelf_add', 'agentgo_cancel', 'agentgo_unclaim', 'agentgo_inbox', 'agentgo_msg'];
|
|
16
|
+
const missing = expected.filter((n) => !names.includes(n));
|
|
17
|
+
console.log(missing.length ? 'MISSING: ' + missing.join(',') : 'ALL EXPECTED TOOLS PRESENT');
|
|
18
|
+
await client.close();
|
|
19
|
+
process.exit(missing.length ? 1 : 0);
|
|
20
|
+
})().catch((e) => { console.error(e); process.exit(2); });
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* 阶段4断言②用:在 staging 以 BUYER 身份 publish 一单(只发布不认领,保持在途) */
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const BASE = 'http://127.0.0.1:18302';
|
|
7
|
+
const KEYS = '/home/hatch/workspace/agentgo/agentgo-mcp/test/keys';
|
|
8
|
+
async function restEvent(ag, kind, payload) {
|
|
9
|
+
const priv = crypto.createPrivateKey(fs.readFileSync(path.join(KEYS, ag, 'private.pem'), 'utf8'));
|
|
10
|
+
const sig = crypto.sign(null, Buffer.from(kind + '\n' + ag + '\n' + JSON.stringify(payload), 'utf8'), priv).toString('hex');
|
|
11
|
+
const r = await fetch(BASE + '/event', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ kind, agent: ag, payload, sig }) });
|
|
12
|
+
const t = await r.text(); let b; try { b = JSON.parse(t); } catch { b = t; }
|
|
13
|
+
return { status: r.status, body: b };
|
|
14
|
+
}
|
|
15
|
+
(async () => {
|
|
16
|
+
const spec = { title: '阶段4锚定测试单-保持在途', description: 'mem5gen fail-closed anchor test', budget: 5, deadline: new Date(Date.now() + 7*864e5).toISOString(), required_capabilities: ["test"], assertions: [{ type: 'file_exists', path: 'result/out.md' }] };
|
|
17
|
+
const r = await restEvent('AG-MCPSTG-BUYER', 'publish', { spec });
|
|
18
|
+
console.log('publish status=', r.status, JSON.stringify(r.body).slice(0, 300));
|
|
19
|
+
})();
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const { connect, call } = require('./harness');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
(async () => {
|
|
4
|
+
process.env.TEST_ELICIT = 'none';
|
|
5
|
+
const c = await connect({ AGENTGO_AGENT_ID: 'AG-MCPSTG-BUYER', AG_KEYS_DIR: path.join(__dirname, 'keys'), AGENTGO_BASE_URL: 'http://127.0.0.1:18302' });
|
|
6
|
+
for (const [n, a] of [['agentgo_search', { query: 'MCP', kind: 'shelf', limit: 3 }], ['agentgo_shop_view', { agent_id: 'AG-MCPSTG-SELLER' }], ['agentgo_agent_reviews', { agent_id: 'AG-MCPSTG-SELLER' }], ['agentgo_agent_record', { agent_id: 'AG-MCPSTG-SELLER' }], ['agentgo_inbox', { limit: 3 }], ['agentgo_ledger', {}]]) {
|
|
7
|
+
const r = await call(c, n, a);
|
|
8
|
+
console.log(n, 'isError=' + r.isError, r.text.slice(0, 140).replace(/\n/g, ' '));
|
|
9
|
+
}
|
|
10
|
+
await c.close();
|
|
11
|
+
})().catch(e => { console.error(e); process.exit(2); });
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/* 验收③:授权拦截实测。
|
|
3
|
+
* A) 主人拒绝 elicitation → buy 不执行、无状态变化(余额不变、商品仍在架、无新任务)。
|
|
4
|
+
* B) 客户端无 elicitation 能力且无授权书 → buy 被 BLOCKED(fail-closed)。
|
|
5
|
+
* C) 授权书覆盖内(per_tx≥价)+ 无 elicitation → buy 直接执行且标注依据,随后正常履约结算。
|
|
6
|
+
* D) 授权书超限(per_tx<价)+ 无 elicitation → 回落 elicitation 仍不可用 → BLOCKED。 */
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const { connect, call } = require('./harness');
|
|
10
|
+
|
|
11
|
+
const BASE = 'http://127.0.0.1:18302';
|
|
12
|
+
const KEYS = path.join(__dirname, 'keys');
|
|
13
|
+
const SELLER = 'AG-MCPSTG-SELLER', BUYER = 'AG-MCPSTG-BUYER';
|
|
14
|
+
const env = (ag, extra = {}) => ({ AGENTGO_AGENT_ID: ag, AG_KEYS_DIR: KEYS, AGENTGO_BASE_URL: BASE, ...extra });
|
|
15
|
+
function j(text) { for (let i = text.indexOf('{'); i >= 0; i = text.indexOf('{', i + 1)) { try { return JSON.parse(text.slice(i)); } catch {} } return null; }
|
|
16
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
17
|
+
|
|
18
|
+
(async () => {
|
|
19
|
+
const say = (s) => console.log(s);
|
|
20
|
+
let fails = 0;
|
|
21
|
+
const expect = (cond, label) => { say(`${cond ? 'PASS' : 'FAIL'}: ${label}`); if (!cond) fails++; };
|
|
22
|
+
|
|
23
|
+
process.env.TEST_ELICIT = 'approve';
|
|
24
|
+
const seller = await connect(env(SELLER));
|
|
25
|
+
const items = [];
|
|
26
|
+
for (let i = 0; i < 3; i++) {
|
|
27
|
+
const add = await call(seller, 'agentgo_shelf_add', { title: '授权拦截测试商品' + i, price: 5, description: 'reject test', deliverable: 'result/x.md', deadline_hours: 720 });
|
|
28
|
+
items.push(j(add.text).item_id);
|
|
29
|
+
}
|
|
30
|
+
say('items: ' + items.join(','));
|
|
31
|
+
const balOf = async (c) => { const o = j((await call(c, 'agentgo_balance', {})).text); return o ? o.available : null; };
|
|
32
|
+
const shelfHas = async (c, item) => { const o = j((await call(c, 'agentgo_shelf_list', {})).text); const arr = (o && (o.items || o.shelf || o.listings)) || []; return Array.isArray(arr) && arr.some((x) => (x.item_id || x.id) === item); };
|
|
33
|
+
|
|
34
|
+
/* A) 拒绝 elicitation */
|
|
35
|
+
process.env.TEST_ELICIT = 'reject';
|
|
36
|
+
const buyerR = await connect(env(BUYER));
|
|
37
|
+
const bBefore = await balOf(buyerR);
|
|
38
|
+
const rA = await call(buyerR, 'agentgo_buy', { item_id: items[0] });
|
|
39
|
+
say('A buy result: isError=' + rA.isError + ' ' + rA.text.slice(0, 160));
|
|
40
|
+
expect(rA.isError && rA.text.includes('BLOCKED'), 'A1 主人拒绝 → buy 被 BLOCKED');
|
|
41
|
+
const bAfter = await balOf(buyerR);
|
|
42
|
+
expect(bBefore === bAfter, `A2 余额无变化 (${bBefore} → ${bAfter})`);
|
|
43
|
+
expect(await shelfHas(buyerR, items[0]), 'A3 商品仍在架(未生成订单)');
|
|
44
|
+
await buyerR.close();
|
|
45
|
+
|
|
46
|
+
/* B) 无 elicitation 能力、无授权书 */
|
|
47
|
+
process.env.TEST_ELICIT = 'none';
|
|
48
|
+
const buyerN = await connect(env(BUYER));
|
|
49
|
+
const rB = await call(buyerN, 'agentgo_buy', { item_id: items[0] });
|
|
50
|
+
say('B buy result: isError=' + rB.isError + ' ' + rB.text.slice(0, 160));
|
|
51
|
+
expect(rB.isError && rB.text.includes('BLOCKED'), 'B 无授权通道 → fail-closed BLOCKED');
|
|
52
|
+
await buyerN.close();
|
|
53
|
+
|
|
54
|
+
/* C) 授权书覆盖内 */
|
|
55
|
+
const mandateFile = path.join(__dirname, 'mandate-test.json');
|
|
56
|
+
fs.writeFileSync(mandateFile, JSON.stringify({ agent: BUYER, actions: ['buy'], limits: { per_tx: 10, daily: 100, monthly: 1000 }, expires_at: '2027-01-01T00:00:00Z', note: '阶段2验收用测试授权书' }, null, 2));
|
|
57
|
+
const spendLog = path.join(__dirname, 'spend-log.json'); try { fs.unlinkSync(spendLog); } catch {}
|
|
58
|
+
process.env.TEST_ELICIT = 'none';
|
|
59
|
+
const buyerM = await connect(env(BUYER, { AGENTGO_MANDATE_FILE: mandateFile }));
|
|
60
|
+
const rC = await call(buyerM, 'agentgo_buy', { item_id: items[1] });
|
|
61
|
+
say('C buy result: isError=' + rC.isError + ' ' + rC.text.slice(0, 220));
|
|
62
|
+
const taskC = j(rC.text) && j(rC.text).task_id;
|
|
63
|
+
expect(!rC.isError && !!taskC && rC.text.includes('预签授权书'), 'C 授权书内 buy 直接执行并标注依据,task=' + taskC);
|
|
64
|
+
// 履约完结这一单
|
|
65
|
+
process.env.TEST_ELICIT = 'approve';
|
|
66
|
+
say('C claim: ' + (await call(seller, 'agentgo_claim', { task: taskC })).text.slice(0, 120));
|
|
67
|
+
const subC = await call(seller, 'agentgo_submit', { task: taskC, result_path: 'result/x.md', content: 'mandate trade deliverable\n' });
|
|
68
|
+
say('C submit: ' + subC.text.slice(0, 200));
|
|
69
|
+
expect(subC.text.includes('"settled": true'), 'C 授权书单正常结算');
|
|
70
|
+
|
|
71
|
+
/* D) 授权书超限 + 无 elicitation */
|
|
72
|
+
fs.writeFileSync(mandateFile, JSON.stringify({ agent: BUYER, actions: ['buy'], limits: { per_tx: 3, daily: 100, monthly: 1000 }, expires_at: '2027-01-01T00:00:00Z' }, null, 2));
|
|
73
|
+
process.env.TEST_ELICIT = 'none';
|
|
74
|
+
const buyerD = await connect(env(BUYER, { AGENTGO_MANDATE_FILE: mandateFile }));
|
|
75
|
+
const rD = await call(buyerD, 'agentgo_buy', { item_id: items[2] });
|
|
76
|
+
say('D buy result: isError=' + rD.isError + ' ' + rD.text.slice(0, 200));
|
|
77
|
+
expect(rD.isError && rD.text.includes('BLOCKED'), 'D 超授权书单笔上限且无 elicitation → BLOCKED');
|
|
78
|
+
expect(await shelfHas(buyerD, items[2]), 'D 商品仍在架');
|
|
79
|
+
await buyerM.close(); await buyerD.close();
|
|
80
|
+
await seller.close();
|
|
81
|
+
say(fails ? `REJECT-TEST FAILURES=${fails}` : 'REJECT-TEST ALL PASS');
|
|
82
|
+
process.exit(fails ? 1 : 0);
|
|
83
|
+
})().catch((e) => { console.error('REJECT-TEST ERROR', e); process.exit(2); });
|