@proxyflow/mcp-server 1.0.0 → 1.1.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
@@ -6,10 +6,26 @@
6
6
 
7
7
  | 工具 | 说明 |
8
8
  |------|------|
9
- | `upsert_mock` | 按 URL pathname(+可选 method)创建或更新一个 mock。已存在时新增一个版本并设为激活版本,不会产生重复规则。 |
10
- | `toggle_mock` | 按 URL pathname(+可选 method)开启/关闭一个已存在的 mock。找不到规则时会提示先调用 `upsert_mock`。 |
11
- | `list_mocks` | 列出当前用户的所有 mock 规则(含版本列表与当前激活版本)。 |
12
- | `wait_for_request` | 阻塞等待下一个匹配该 URL pathname(+可选 method)的真实请求经过代理,返回其抓包结果。适合在关闭 mock 后,触发一次真实调用来获取真实响应结构。 |
9
+ | `upsert_mock` | 按 URL pathname(+可选 method)创建/更新 mock。幂等:已存在则更新规则并新增版本(内容完全相同则复用,不会堆重复版本)。支持 `:id` 路径参数、`version_name` 场景命名、`activate:false` 只存不切换、`condition`(按 query/header/body 字段返回不同 mock)、`from_request_id`(把抓到的真实响应原样存为 mock)。 |
10
+ | `toggle_mock` | 开启/关闭 mock。不传 `method` 时作用于该路径的所有规则;找不到时提示先 `upsert_mock`。 |
11
+ | `list_mocks` | 列出 mock 规则(精简输出:版本列表 + 当前激活版本),`include_body` 可附带激活版本的响应体。 |
12
+ | `switch_mock_version` | 在同一接口的多个场景(成功/空列表/报错…)之间切换激活版本,按 `version_name` 或 `version_id`。 |
13
+ | `delete_mock` | 删除某路径+方法的 mock(严格匹配,不传 method ≠ 所有方法)。 |
14
+ | `wait_for_request` | 阻塞等待匹配的真实请求经过代理并返回抓包结果。`lookback_ms` 可回溯已发生的请求,`only_real` 忽略被 mock 命中的请求;返回中 `source` 标明 MOCK/REAL,敏感请求头(Authorization/Cookie 等)自动打码,过大的 body 自动截断。 |
15
+ | `list_recent_requests` | 最近抓到的请求摘要(id/时间/方法/URL/状态/来源),可按 URL、方法、状态(`404` / `5xx`)过滤。 |
16
+ | `get_request` | 按 id 查看单个请求的完整详情(同样打码 + 截断)。 |
17
+
18
+ > 只有经过 proxyflow(已配对设备的 SDK relay,或带 `x-proxyflow-session` 头的代理请求)的流量才会被 mock / 抓取。
19
+ > mock 只按 **pathname** 匹配(忽略域名和 query);需要按 query/header/body 区分时用 `condition`。
20
+ > 多条规则同时命中时的优先级:带 condition > exact > wildcard(`*` 越少越优先) > regex。
21
+
22
+ ## 典型流程
23
+
24
+ 1. 设计好接口 → `upsert_mock` 立刻给前端/客户端一个可用的假数据;
25
+ 2. 后端写好后 → `toggle_mock enabled=false`,让 App 触发一次真实请求 → `wait_for_request` 看真实结构;
26
+ 3. `upsert_mock` 带 `from_request_id` 把真实响应存成 mock(或据此微调);
27
+ 4. `switch_mock_version` 在成功/空/错误场景间切换,验证客户端各分支;
28
+ 5. 完成后 `delete_mock` 清理。
13
29
 
14
30
  ## 获取 Token
15
31
 
@@ -88,8 +104,21 @@ claude mcp add proxyflow \
88
104
  | `PROXYFLOW_URL` | 是 | proxyflow 后端地址,例如 `http://localhost:9000` |
89
105
  | `PROXYFLOW_TOKEN` | 是 | 在设置页生成的 API Token,`pf_` 开头 |
90
106
 
107
+ ## 测试
108
+
109
+ `test/e2e.mjs` 通过 stdio 启动构建后的 MCP,对一个运行中的 proxyflow 后端跑全部工具的端到端用例(含边界/故障场景)。
110
+ 它会注册一个临时用户并创建 mock,**请对测试后端运行,不要指向你的真实库**:
111
+
112
+ ```bash
113
+ # 在一份临时拷贝(独立 DB)里起后端:PORT=19000 PROXY_PORT=19001 bun src/index.ts
114
+ PROXYFLOW_URL=http://localhost:19000 npm run test:e2e
115
+ ```
116
+
91
117
  ## 发布(维护者)
92
118
 
119
+ > ⚠️ 本版本的新工具依赖后端新增的接口,**请先部署后端(`npm run deploy`),再 `npm publish` MCP**。旧版 MCP 连新版后端是兼容的,反之不行。
120
+
121
+
93
122
  ```bash
94
123
  cd mcp-server
95
124
  npm version <patch|minor|major>
package/dist/format.js ADDED
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ // Pure helpers that shape backend payloads into something an LLM can consume cheaply and safely.
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.DEFAULT_MAX_BODY_CHARS = void 0;
5
+ exports.parseJsonField = parseJsonField;
6
+ exports.redactHeaders = redactHeaders;
7
+ exports.shapeBody = shapeBody;
8
+ exports.summariseLog = summariseLog;
9
+ exports.detailLog = detailLog;
10
+ exports.condenseRule = condenseRule;
11
+ const SENSITIVE_HEADERS = new Set([
12
+ 'authorization', 'proxy-authorization', 'cookie', 'set-cookie',
13
+ 'x-api-key', 'x-auth-token', 'x-access-token', 'x-csrf-token', 'x-xsrf-token',
14
+ ]);
15
+ exports.DEFAULT_MAX_BODY_CHARS = 6000;
16
+ /** Backend log rows store headers/bodies as JSON strings; the /wait endpoint has already parsed them. */
17
+ function parseJsonField(value, expect = 'any') {
18
+ if (typeof value !== 'string')
19
+ return value;
20
+ const t = value.trimStart();
21
+ if (expect === 'object' || t.startsWith('{') || t.startsWith('[')) {
22
+ try {
23
+ return JSON.parse(value);
24
+ }
25
+ catch { /* keep raw */ }
26
+ }
27
+ return value;
28
+ }
29
+ function redactHeaders(headers) {
30
+ if (!headers || typeof headers !== 'object' || Array.isArray(headers))
31
+ return {};
32
+ const out = {};
33
+ for (const [k, v] of Object.entries(headers)) {
34
+ const lower = k.toLowerCase();
35
+ const sensitive = SENSITIVE_HEADERS.has(lower) || /token|secret|session|signature/.test(lower);
36
+ out[k] = sensitive ? '[REDACTED]' : String(v);
37
+ }
38
+ return out;
39
+ }
40
+ /** Keep parsed JSON as-is when small; otherwise cut the serialised form and say so. */
41
+ function shapeBody(body, maxChars) {
42
+ if (body === null || body === undefined)
43
+ return { body: null };
44
+ const serialised = typeof body === 'string' ? body : JSON.stringify(body);
45
+ if (serialised.length <= maxChars)
46
+ return { body };
47
+ return {
48
+ body: serialised.slice(0, maxChars) + ` …[truncated, ${serialised.length - maxChars} more chars]`,
49
+ truncated: true,
50
+ original_chars: serialised.length,
51
+ };
52
+ }
53
+ function summariseLog(log) {
54
+ return {
55
+ id: log.id,
56
+ time: log.created_at,
57
+ method: log.method,
58
+ url: log.url,
59
+ status: log.response_status,
60
+ source: log.is_mocked ? 'MOCK' : 'REAL',
61
+ ...(log.is_mocked && log.mock_id != null ? { mock_id: log.mock_id } : {}),
62
+ duration_ms: log.duration_ms,
63
+ };
64
+ }
65
+ function detailLog(log, maxBodyChars) {
66
+ const reqBody = shapeBody(parseJsonField(log.request_body), maxBodyChars);
67
+ const resBody = shapeBody(parseJsonField(log.response_body), maxBodyChars);
68
+ const notes = [];
69
+ if (log.is_mocked) {
70
+ notes.push('This response came from a MOCK rule, not the real backend. Disable the mock (toggle_mock enabled=false) and retrigger to capture the real shape.');
71
+ }
72
+ if (reqBody.truncated || resBody.truncated) {
73
+ notes.push('Body was truncated for display. To save the exact original response as a mock, call upsert_mock with from_request_id=' + log.id + ' instead of re-typing the body.');
74
+ }
75
+ return {
76
+ ...summariseLog(log),
77
+ request: {
78
+ headers: redactHeaders(parseJsonField(log.request_headers, 'object')),
79
+ body: reqBody.body,
80
+ ...(reqBody.truncated ? { truncated: true, original_chars: reqBody.original_chars } : {}),
81
+ },
82
+ response: {
83
+ headers: redactHeaders(parseJsonField(log.response_headers, 'object')),
84
+ body: resBody.body,
85
+ ...(resBody.truncated ? { truncated: true, original_chars: resBody.original_chars } : {}),
86
+ },
87
+ ...(notes.length ? { notes } : {}),
88
+ };
89
+ }
90
+ function condenseRule(rule, opts = {}) {
91
+ const av = rule.active_version;
92
+ let activeBody;
93
+ if (opts.includeBody && av) {
94
+ let parsed = av.response_body;
95
+ try {
96
+ parsed = JSON.parse(av.response_body);
97
+ }
98
+ catch { /* keep string */ }
99
+ activeBody = shapeBody(parsed, opts.maxBodyChars ?? exports.DEFAULT_MAX_BODY_CHARS).body;
100
+ }
101
+ return {
102
+ rule_id: rule.id,
103
+ name: rule.name,
104
+ url_pattern: rule.url_pattern,
105
+ method: rule.method ?? 'ANY',
106
+ match_type: rule.match_type,
107
+ enabled: !!rule.is_active,
108
+ delay_ms: rule.delay_ms,
109
+ ...(rule.folder_name ? { folder: rule.folder_name } : {}),
110
+ ...(rule.condition_field_type
111
+ ? { condition: { type: rule.condition_field_type, key: rule.condition_field_key, value: rule.condition_field_value } }
112
+ : {}),
113
+ active_version: av ? { id: av.id, name: av.name, status: av.response_status } : null,
114
+ versions: (rule.versions ?? []).map((v) => ({ id: v.id, name: v.name, status: v.response_status, active: v.id === rule.active_version_id })),
115
+ ...(opts.includeBody && av ? { active_body: activeBody } : {}),
116
+ };
117
+ }
package/dist/index.js CHANGED
@@ -1,9 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
3
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const node_path_1 = __importDefault(require("node:path"));
4
9
  const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
5
10
  const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
6
11
  const zod_1 = require("zod");
12
+ const format_js_1 = require("./format.js");
7
13
  const PROXYFLOW_URL = process.env.PROXYFLOW_URL;
8
14
  const PROXYFLOW_TOKEN = process.env.PROXYFLOW_TOKEN;
9
15
  if (!PROXYFLOW_URL || !PROXYFLOW_TOKEN) {
@@ -13,78 +19,256 @@ if (!PROXYFLOW_URL || !PROXYFLOW_TOKEN) {
13
19
  process.exit(1);
14
20
  }
15
21
  const baseUrl = PROXYFLOW_URL.replace(/\/+$/, '');
16
- async function call(path, init) {
17
- const res = await fetch(`${baseUrl}${path}`, {
18
- ...init,
19
- headers: {
20
- 'Content-Type': 'application/json',
21
- Authorization: `Bearer ${PROXYFLOW_TOKEN}`,
22
- ...(init.headers || {}),
23
- },
24
- });
25
- let body;
22
+ const VERSION = (() => {
26
23
  try {
27
- body = await res.json();
24
+ return JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(__dirname, '..', 'package.json'), 'utf8')).version;
28
25
  }
29
26
  catch {
30
- body = await res.text();
27
+ return '0.0.0';
31
28
  }
32
- return { ok: res.ok, status: res.status, body };
33
- }
34
- function toResult(result) {
35
- const text = JSON.stringify(result.body, null, 2);
36
- if (!result.ok) {
37
- return { isError: true, content: [{ type: 'text', text: `HTTP ${result.status}: ${text}` }] };
29
+ })();
30
+ async function call(pathname, init, timeoutMs = 15_000) {
31
+ try {
32
+ const res = await fetch(`${baseUrl}${pathname}`, {
33
+ ...init,
34
+ signal: AbortSignal.timeout(timeoutMs),
35
+ headers: {
36
+ 'Content-Type': 'application/json',
37
+ Authorization: `Bearer ${PROXYFLOW_TOKEN}`,
38
+ ...(init.headers || {}),
39
+ },
40
+ });
41
+ const raw = await res.text();
42
+ let body = raw;
43
+ try {
44
+ body = JSON.parse(raw);
45
+ }
46
+ catch { /* non-JSON body, keep text */ }
47
+ return { ok: res.ok, status: res.status, body };
38
48
  }
39
- return { content: [{ type: 'text', text }] };
49
+ catch (err) {
50
+ const e = err;
51
+ const reason = e.name === 'TimeoutError'
52
+ ? `no response within ${Math.round(timeoutMs / 1000)}s`
53
+ : (e.cause?.code || e.message);
54
+ return {
55
+ ok: false,
56
+ status: 0,
57
+ body: { error: `Cannot reach proxyflow backend at ${baseUrl} (${reason}). Check that the backend is running and PROXYFLOW_URL is correct.` },
58
+ };
59
+ }
60
+ }
61
+ function text(value) {
62
+ return typeof value === 'string' ? value : JSON.stringify(value);
63
+ }
64
+ function fail(result) {
65
+ const detail = text(result.body);
66
+ let hint = '';
67
+ if (result.status === 401)
68
+ hint = '\nHint: PROXYFLOW_TOKEN was rejected — it may be revoked or mistyped. Generate a new one in the proxyflow console (Settings → API Tokens).';
69
+ return { isError: true, content: [{ type: 'text', text: (result.status ? `HTTP ${result.status}: ` : '') + detail + hint }] };
40
70
  }
41
- const server = new mcp_js_1.McpServer({ name: 'proxyflow-mcp', version: '1.0.0' });
42
- const responseHeadersSchema = zod_1.z.record(zod_1.z.string()).optional()
43
- .describe('Response headers, e.g. {"Content-Type": "application/json"}');
44
- const responseBodySchema = zod_1.z.union([zod_1.z.string(), zod_1.z.record(zod_1.z.any()), zod_1.z.array(zod_1.z.any())]).optional()
45
- .describe('Response body — a JSON string or a JSON value');
46
- server.tool('upsert_mock', 'Create or update a mock for an API endpoint, matched by URL pathname (+ optional method). ' +
47
- 'If a mock already exists for the same pathname/method, adds a new version and makes it active instead of creating a duplicate rule. ' +
48
- 'Use this right after creating a new backend endpoint during development so the frontend/mobile client can call it against a mock immediately.', {
49
- url_pattern: zod_1.z.string().describe('Full URL or path of the endpoint, e.g. "/api/users/123" or "https://api.example.com/users/123". Only the pathname is used for matching.'),
50
- method: zod_1.z.string().optional().describe('HTTP method, e.g. "GET", "POST". Omit to match any method.'),
51
- response_status: zod_1.z.number().int().optional().describe('HTTP status code to return. Defaults to 200.'),
52
- response_body: responseBodySchema,
53
- response_headers: responseHeadersSchema,
54
- match_type: zod_1.z.enum(['exact', 'wildcard']).optional().describe('Defaults to "wildcard".'),
55
- name: zod_1.z.string().optional().describe('Human-readable name for the mock rule/version.'),
56
- delay_ms: zod_1.z.number().int().min(0).max(60000).optional().describe('Artificial response delay in milliseconds.'),
57
- enabled: zod_1.z.boolean().optional().describe('Whether the mock should be active. Defaults to true.'),
58
- }, async (args) => toResult(await call('/api/mocks/upsert', { method: 'POST', body: JSON.stringify(args) })));
59
- server.tool('toggle_mock', 'Enable or disable an existing mock, matched by URL pathname (+ optional method). ' +
60
- 'Returns a 404-style error if no mock exists yet for that pathname/method — call upsert_mock first in that case.', {
61
- url_pattern: zod_1.z.string().describe('Full URL or path of the endpoint. Only the pathname is used for matching.'),
62
- method: zod_1.z.string().optional().describe('HTTP method. Omit to match the rule with no method restriction.'),
63
- enabled: zod_1.z.boolean().describe('true to enable the mock, false to disable it (fall through to the real backend/proxy).'),
64
- }, async (args) => toResult(await call('/api/rules/toggle-by-pattern', { method: 'PATCH', body: JSON.stringify(args) })));
65
- server.tool('list_mocks', 'List all mock rules for the current user, including their versions and which version is active.', {
66
- search: zod_1.z.string().optional().describe('Filter by rule name or URL pattern substring.'),
67
- }, async ({ search }) => {
71
+ /** Send `result` back to the model, optionally reshaping a successful body. */
72
+ function respond(result, shape) {
73
+ if (!result.ok)
74
+ return fail(result);
75
+ return { content: [{ type: 'text', text: text(shape ? shape(result.body) : result.body) }] };
76
+ }
77
+ // ── Server & tools ────────────────────────────────────────────────────────
78
+ const server = new mcp_js_1.McpServer({ name: 'proxyflow-mcp', version: VERSION }, {
79
+ instructions: 'proxyflow mocks HTTP APIs for a mobile/mini-program/web client. Typical loop when developing a new endpoint: ' +
80
+ '(1) upsert_mock to serve a fake response immediately; (2) once the real backend exists, toggle_mock enabled=false, ' +
81
+ 'ask the user to trigger the call in the app, then wait_for_request (or list_recent_requests if it already fired) to see the real shape; ' +
82
+ '(3) upsert_mock with from_request_id to save the exact real response, or adjust the mock; (4) switch_mock_version to flip between ' +
83
+ 'scenarios (success / empty / error) and delete_mock to clean up. Only requests routed through a paired proxyflow device/session are mocked or captured.',
84
+ });
85
+ const READ_ONLY = { readOnlyHint: true, openWorldHint: false };
86
+ const WRITE_IDEMPOTENT = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };
87
+ const urlPatternField = zod_1.z.string().min(1).describe('Full URL or path of the endpoint, e.g. "/api/users/123" or "https://api.example.com/users/123". ' +
88
+ 'Only the pathname is used (host and query string are ignored). Use "*" as a wildcard and ":id" or "{id}" for path parameters, e.g. "/api/users/:id".');
89
+ const methodField = zod_1.z.string().optional().describe('HTTP method, e.g. "GET", "POST" (case-insensitive). Omit to not restrict by method.');
90
+ const maxBodyField = zod_1.z.number().int().min(200).max(100000).optional()
91
+ .describe(`Max characters of each body to return (default ${format_js_1.DEFAULT_MAX_BODY_CHARS}). Larger bodies are truncated.`);
92
+ server.registerTool('upsert_mock', {
93
+ title: 'Create or update a mock',
94
+ description: 'Create or update a mock for an API endpoint, matched by URL pathname (+ optional method). ' +
95
+ 'Idempotent: an existing rule for the same pathname/method/condition is updated in place, and a new response is stored as a new version and activated ' +
96
+ '(an identical response reuses the existing version, so repeated calls never pile up duplicates). ' +
97
+ 'Use it right after designing/creating an endpoint so the client can call it against a mock immediately, or with from_request_id to freeze a real captured response as the mock.',
98
+ inputSchema: {
99
+ url_pattern: urlPatternField,
100
+ method: methodField,
101
+ response_status: zod_1.z.number().int().min(100).max(599).optional().describe('HTTP status code to return. Defaults to 200.'),
102
+ response_body: zod_1.z.union([zod_1.z.string(), zod_1.z.record(zod_1.z.any()), zod_1.z.array(zod_1.z.any())]).optional()
103
+ .describe('Response body. An object/array is serialised as JSON; a string is sent verbatim. Defaults to {} (or the captured body when from_request_id is set).'),
104
+ response_headers: zod_1.z.record(zod_1.z.string()).optional()
105
+ .describe('Response headers, e.g. {"Content-Type": "application/json"}. Defaults to JSON (text/plain for a non-JSON string body).'),
106
+ match_type: zod_1.z.enum(['exact', 'wildcard', 'regex']).optional()
107
+ .describe('Defaults to "wildcard" on create; left unchanged on update. Path parameters (":id") force wildcard.'),
108
+ name: zod_1.z.string().optional().describe('Human-readable name of the rule (defaults to the pathname).'),
109
+ version_name: zod_1.z.string().optional()
110
+ .describe('Name of this response scenario, e.g. "success", "empty-list", "server-error". Used by switch_mock_version. Defaults to name or the status code.'),
111
+ delay_ms: zod_1.z.number().int().min(0).max(60000).optional().describe('Artificial response delay in milliseconds (kept as-is on update when omitted).'),
112
+ enabled: zod_1.z.boolean().optional().describe('Whether the mock is active. Defaults to true on create; unchanged on update when omitted.'),
113
+ activate: zod_1.z.boolean().optional()
114
+ .describe('Set false to store this response as an alternate version WITHOUT making it the active one. Defaults to true.'),
115
+ condition: zod_1.z.object({
116
+ type: zod_1.z.enum(['header', 'query', 'body']),
117
+ key: zod_1.z.string().min(1),
118
+ value: zod_1.z.string().min(1),
119
+ }).optional().describe('Only serve this mock when the request has header/query param/JSON body field `key` equal to `value`. Lets one endpoint return different mocks per input. Rules with a condition take priority.'),
120
+ from_request_id: zod_1.z.number().int().optional()
121
+ .describe('Copy status, headers and body from a captured request (request log id from wait_for_request / list_recent_requests). Explicit response_* fields still override.'),
122
+ },
123
+ annotations: WRITE_IDEMPOTENT,
124
+ }, async (args) => respond(await call('/api/mocks/upsert', { method: 'POST', body: JSON.stringify(args) }), (b) => ({
125
+ ...(0, format_js_1.condenseRule)(b),
126
+ created: b.created,
127
+ saved_version_id: b.saved_version_id,
128
+ version_reused: b.version_reused,
129
+ tip: b.is_active
130
+ ? 'Live: requests through a paired proxyflow device matching this rule now receive the active version.'
131
+ : 'Rule is DISABLED — requests go to the real backend until toggle_mock enabled=true.',
132
+ })));
133
+ server.registerTool('toggle_mock', {
134
+ title: 'Enable or disable a mock',
135
+ description: 'Enable or disable existing mock(s), matched by URL pathname (+ optional method). ' +
136
+ 'Without `method`, every rule for that pathname is toggled; with it, only that method\'s rule. ' +
137
+ 'Returns an error if nothing matches — call upsert_mock first in that case. ' +
138
+ 'Disable a mock (enabled=false) so the next call falls through to the real backend.',
139
+ inputSchema: {
140
+ url_pattern: urlPatternField,
141
+ method: methodField,
142
+ enabled: zod_1.z.boolean().describe('true to enable the mock, false to disable it (fall through to the real backend).'),
143
+ },
144
+ annotations: WRITE_IDEMPOTENT,
145
+ }, async (args) => respond(await call('/api/rules/toggle-by-pattern', { method: 'PATCH', body: JSON.stringify(args) })));
146
+ server.registerTool('list_mocks', {
147
+ title: 'List mocks',
148
+ description: 'List the current user\'s mock rules with their versions and which one is active. ' +
149
+ 'Compact by default; set include_body to also see each active response body.',
150
+ inputSchema: {
151
+ search: zod_1.z.string().optional().describe('Filter by rule name or URL pattern substring.'),
152
+ include_body: zod_1.z.boolean().optional().describe('Include the active version\'s response body (truncated). Default false.'),
153
+ max_body_chars: maxBodyField,
154
+ },
155
+ annotations: READ_ONLY,
156
+ }, async ({ search, include_body, max_body_chars }) => {
68
157
  const qs = search ? `?search=${encodeURIComponent(search)}` : '';
69
- return toResult(await call(`/api/mocks${qs}`, { method: 'GET' }));
158
+ return respond(await call(`/api/mocks${qs}`, { method: 'GET' }), (rules) => ({
159
+ count: rules.length,
160
+ mocks: rules.map((r) => (0, format_js_1.condenseRule)(r, { includeBody: include_body, maxBodyChars: max_body_chars })),
161
+ }));
70
162
  });
71
- server.tool('wait_for_request', 'Block until the next real HTTP request matching a URL pathname (+ optional method) passes through the proxy, then return its captured request/response. ' +
72
- 'Useful for discovering the real shape of a new endpoint before writing its mock — disable/skip the mock first, trigger the call from the client, and use this tool to capture what actually happened.', {
73
- url_pattern: zod_1.z.string().describe('Full URL or path of the endpoint. Only the pathname is used for matching.'),
74
- method: zod_1.z.string().optional().describe('HTTP method to filter on. Omit to match any method.'),
75
- timeout_ms: zod_1.z.number().int().min(1000).max(60000).optional().describe('Max time to wait, in milliseconds. Defaults to 30000, clamped to [1000, 60000].'),
76
- }, async ({ url_pattern, method, timeout_ms }) => {
163
+ server.registerTool('wait_for_request', {
164
+ title: 'Wait for a real request',
165
+ description: 'Block until a request matching a URL pathname (+ optional method) passes through proxyflow, then return its captured request and response ' +
166
+ '(sensitive headers such as Authorization/Cookie are redacted; large bodies are truncated). ' +
167
+ 'Use it to discover the real shape of an endpoint: disable the mock first (toggle_mock enabled=false), ask the user to trigger the call in the app, then call this. ' +
168
+ 'If the request may already have fired, set lookback_ms to include recent history. Check `source`: MOCK means the answer came from a mock, not the real backend.',
169
+ inputSchema: {
170
+ url_pattern: urlPatternField,
171
+ method: zod_1.z.string().optional().describe('HTTP method to filter on. Omit to match any method.'),
172
+ timeout_ms: zod_1.z.number().int().min(1000).max(60000).optional().describe('Max time to wait, in milliseconds. Defaults to 30000.'),
173
+ lookback_ms: zod_1.z.number().int().min(0).max(300000).optional()
174
+ .describe('Also accept a matching request captured up to this many ms ago (returns the most recent). Default 0 = only future requests.'),
175
+ only_real: zod_1.z.boolean().optional().describe('Ignore requests that were answered by a mock. Default false.'),
176
+ max_body_chars: maxBodyField,
177
+ },
178
+ annotations: READ_ONLY,
179
+ }, async ({ url_pattern, method, timeout_ms, lookback_ms, only_real, max_body_chars }) => {
77
180
  const params = new URLSearchParams({ url_pattern });
78
181
  if (method)
79
182
  params.set('method', method);
80
183
  if (timeout_ms)
81
184
  params.set('timeout_ms', String(timeout_ms));
82
- return toResult(await call(`/api/requests/wait?${params.toString()}`, { method: 'GET' }));
185
+ if (lookback_ms)
186
+ params.set('lookback_ms', String(lookback_ms));
187
+ if (only_real)
188
+ params.set('only_real', 'true');
189
+ const result = await call(`/api/requests/wait?${params}`, { method: 'GET' }, (timeout_ms ?? 30_000) + 10_000);
190
+ return respond(result, (b) => b.matched
191
+ ? { matched: true, waited_ms: b.waited_ms, ...(0, format_js_1.detailLog)(b.request, max_body_chars ?? format_js_1.DEFAULT_MAX_BODY_CHARS) }
192
+ : {
193
+ matched: false,
194
+ waited_ms: b.waited_ms,
195
+ hint: 'No matching request arrived. Make sure the client is paired to proxyflow (Devices page) and actually sends this call; ' +
196
+ 'try lookback_ms if it already fired, or list_recent_requests to see what did pass through.',
197
+ });
198
+ });
199
+ server.registerTool('list_recent_requests', {
200
+ title: 'List recent captured requests',
201
+ description: 'List the most recent requests captured by proxyflow (newest first) as compact summaries: id, time, method, url, status and whether it was MOCK or REAL. ' +
202
+ 'Each row\'s `id` is a REQUEST LOG id — pass it to get_request / upsert_mock from_request_id. It is NOT a mock rule_id or version id (those come from list_mocks). ' +
203
+ 'MOCK rows also carry `mock_id` (the rule that answered). ' +
204
+ 'Use it to see what the client actually called or to find failing calls (status="4xx"/"5xx"), then get_request for full details.',
205
+ inputSchema: {
206
+ url_contains: zod_1.z.string().optional().describe('Substring the URL must contain, e.g. "/api/orders".'),
207
+ method: zod_1.z.string().optional().describe('HTTP method filter.'),
208
+ status: zod_1.z.string().optional().describe('Exact status ("404") or a class ("4xx", "5xx").'),
209
+ only_real: zod_1.z.boolean().optional().describe('Exclude requests answered by a mock.'),
210
+ limit: zod_1.z.number().int().min(1).max(50).optional().describe('Max rows to return. Default 10.'),
211
+ },
212
+ annotations: READ_ONLY,
213
+ }, async ({ url_contains, method, status, only_real, limit }) => {
214
+ const want = limit ?? 10;
215
+ const params = new URLSearchParams({ limit: String(only_real ? Math.min(want * 4, 200) : want) });
216
+ if (url_contains)
217
+ params.set('url', url_contains);
218
+ if (method)
219
+ params.set('method', method);
220
+ if (status)
221
+ params.set('status', status);
222
+ return respond(await call(`/api/requests?${params}`, { method: 'GET' }), (b) => {
223
+ const logs = b.logs.filter((l) => l.method !== 'CONNECT' && (!only_real || !l.is_mocked)).slice(0, want);
224
+ return { returned: logs.length, requests: logs.map(format_js_1.summariseLog) };
225
+ });
83
226
  });
227
+ server.registerTool('get_request', {
228
+ title: 'Get one captured request',
229
+ description: 'Full details of one captured request by its request log id (the `id` field from list_recent_requests or wait_for_request): request/response headers (sensitive ones redacted) and bodies (truncated if large). ' +
230
+ 'Do NOT pass a mock rule_id or version id from list_mocks — those are different ids and will 404 or return an unrelated request.',
231
+ inputSchema: {
232
+ id: zod_1.z.number().int().describe('Request log id — the `id` from list_recent_requests / wait_for_request (NOT a mock rule_id or version id from list_mocks).'),
233
+ max_body_chars: maxBodyField,
234
+ },
235
+ annotations: READ_ONLY,
236
+ }, async ({ id, max_body_chars }) => respond(await call(`/api/requests/${id}`, { method: 'GET' }), (log) => (0, format_js_1.detailLog)(log, max_body_chars ?? format_js_1.DEFAULT_MAX_BODY_CHARS)));
237
+ server.registerTool('switch_mock_version', {
238
+ title: 'Switch the active mock version',
239
+ description: 'Make a different stored response ("version"/scenario) the active one for a mock — e.g. flip between success, empty list and server error to test client handling. ' +
240
+ 'Identify the version by version_name (as set via upsert_mock version_name) or version_id (from list_mocks). Errors list the available versions.',
241
+ inputSchema: {
242
+ url_pattern: urlPatternField,
243
+ method: methodField,
244
+ version_name: zod_1.z.string().optional().describe('Name of the version to activate (the newest one with that name wins).'),
245
+ version_id: zod_1.z.number().int().optional().describe('Id of the version to activate.'),
246
+ },
247
+ annotations: WRITE_IDEMPOTENT,
248
+ }, async (args) => respond(await call('/api/mocks/switch-version', { method: 'POST', body: JSON.stringify(args) }), (b) => ({ ...(0, format_js_1.condenseRule)(b), switched_to: b.switched_to })));
249
+ server.registerTool('delete_mock', {
250
+ title: 'Delete a mock',
251
+ description: 'Permanently delete the mock rule(s) (with all versions) for a URL pathname + method. Deletion is strict: an omitted method means the rule with no method restriction, not every method. ' +
252
+ 'To merely stop mocking, use toggle_mock enabled=false instead. Use this to clean up temporary mocks when the real endpoint is done.',
253
+ inputSchema: {
254
+ url_pattern: urlPatternField,
255
+ method: methodField,
256
+ },
257
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
258
+ }, async (args) => respond(await call('/api/mocks/delete-by-pattern', { method: 'POST', body: JSON.stringify(args) })));
259
+ // ── Startup ───────────────────────────────────────────────────────────────
84
260
  async function main() {
85
261
  const transport = new stdio_js_1.StdioServerTransport();
86
262
  await server.connect(transport);
87
- console.error(`[proxyflow-mcp] connected — backend ${baseUrl}`);
263
+ console.error(`[proxyflow-mcp] v${VERSION} connected — backend ${baseUrl}`);
264
+ // Non-fatal preflight so misconfiguration shows up in the client's MCP logs right away.
265
+ const me = await call('/api/auth/me', { method: 'GET' }, 5_000);
266
+ if (me.ok)
267
+ console.error('[proxyflow-mcp] token OK');
268
+ else if (me.status === 401)
269
+ console.error('[proxyflow-mcp] WARNING: PROXYFLOW_TOKEN was rejected by the backend (invalid or revoked).');
270
+ else
271
+ console.error(`[proxyflow-mcp] WARNING: ${text(me.body)}`);
88
272
  }
89
273
  main().catch((err) => {
90
274
  console.error('[proxyflow-mcp] fatal error', err);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@proxyflow/mcp-server",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "proxyflow MCP server — 让 AI 助手在开发新接口时自行 mock/切换/等待请求",
5
5
  "main": "dist/index.js",
6
6
  "publishConfig": {
@@ -15,6 +15,7 @@
15
15
  "scripts": {
16
16
  "build": "tsc",
17
17
  "start": "node dist/index.js",
18
+ "test:e2e": "npm run build && node test/e2e.mjs",
18
19
  "prepublishOnly": "npm run build"
19
20
  },
20
21
  "keywords": [
@@ -28,7 +29,7 @@
28
29
  "node": ">=18"
29
30
  },
30
31
  "dependencies": {
31
- "@modelcontextprotocol/sdk": "^1.12.0",
32
+ "@modelcontextprotocol/sdk": "^1.30.0",
32
33
  "zod": "^3.23.8"
33
34
  },
34
35
  "devDependencies": {