@meterbox/mcp 0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Meterbox Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,106 @@
1
+ # @meterbox/mcp
2
+
3
+ The [Model Context Protocol](https://modelcontextprotocol.io) server for
4
+ [Meterbox](https://meterbox.ai). Every Meterbox deployment serves it at
5
+ `<your Meterbox host>/mcp/sandbox` and `/mcp/production`; this package is the
6
+ same code, plus a `meterbox-mcp` command that bridges stdio-only MCP clients
7
+ to that endpoint.
8
+
9
+ ## Connect
10
+
11
+ Create an **agent key** in Meterbox under Settings > API keys. Agent keys work
12
+ only with MCP, belong to one environment (`mb_agent_sandbox_...` or
13
+ `mb_agent_production_...`), and are read-only unless you choose otherwise.
14
+
15
+ Keep the key in an environment variable rather than pasting it into config
16
+ files:
17
+
18
+ ```bash
19
+ export METERBOX_AGENT_KEY=mb_agent_sandbox_...
20
+ ```
21
+
22
+ **Claude Code**
23
+
24
+ ```bash
25
+ claude mcp add --transport http meterbox-sandbox https://meterbox.ai/mcp/sandbox \
26
+ --header "Authorization: Bearer ${METERBOX_AGENT_KEY}"
27
+ ```
28
+
29
+ **Any client that runs a local command (stdio)**
30
+
31
+ ```json
32
+ {
33
+ "mcpServers": {
34
+ "meterbox-sandbox": {
35
+ "command": "npx",
36
+ "args": ["-y", "@meterbox/mcp"],
37
+ "env": {
38
+ "METERBOX_BASE_URL": "https://meterbox.ai",
39
+ "METERBOX_AGENT_KEY": "${METERBOX_AGENT_KEY}"
40
+ }
41
+ }
42
+ }
43
+ }
44
+ ```
45
+
46
+ The key's prefix picks the environment. Add `"--toolsets", "catalog,customers"`
47
+ to `args` to expose only some toolsets; this can narrow what the key allows but
48
+ never widen it. On a self-hosted deployment, use your own host instead of
49
+ `https://meterbox.ai`.
50
+
51
+ Requires Node.js 20 or later.
52
+
53
+ ## Tools
54
+
55
+ Seven tools cover the whole `/v1` API instead of one tool per endpoint:
56
+
57
+ | Tool | What it does |
58
+ | ----------------------------- | ---------------------------------------------------------- |
59
+ | `meterbox_whoami` | Environment, access level, toolsets and available tools |
60
+ | `meterbox_search_operations` | Find operations by keyword, toolset or tier |
61
+ | `meterbox_describe_operation` | One operation's path, query and body inputs |
62
+ | `meterbox_read` | Run a read operation (GETs, previews, quotes, simulations) |
63
+ | `meterbox_create` | Run an operation that only adds records |
64
+ | `meterbox_update` | Run an operation that changes records or settings |
65
+ | `meterbox_destructive` | Run an irreversible or money-moving operation |
66
+
67
+ Which tools a connection gets depends on its key:
68
+
69
+ - **Read-only keys** get the first four.
70
+ - **Read-write sandbox keys** also get `meterbox_create` and `meterbox_update`,
71
+ and `meterbox_destructive` when the sandbox's billing provider isn't
72
+ connected in live mode.
73
+ - **Production keys** are read-only over MCP. Use the dashboard for production
74
+ changes.
75
+
76
+ Each execute tool only runs operations of its own tier, so a tool marked
77
+ read-only can never make a change. Operations that return or set credentials,
78
+ configure outbound destinations (webhooks, emails, data sinks), create
79
+ checkout or portal sessions, or export data in bulk are not available over
80
+ MCP at all, and secret-shaped values are removed from every result.
81
+
82
+ ## Hosting it yourself
83
+
84
+ Meterbox deployments already run this server. To embed it elsewhere:
85
+
86
+ ```js
87
+ const { buildCatalog, createServerFactory, createHttpHandler } = require("@meterbox/mcp");
88
+
89
+ const catalog = buildCatalog(openApiSpec);
90
+ const factory = createServerFactory({
91
+ catalog,
92
+ dispatch: async (op, { pathParams, query, body }, { principal }) => {
93
+ // call the API for this principal; resolve { status, body }
94
+ },
95
+ apiReferenceUrl: "https://your-host/docs",
96
+ });
97
+ const mcp = createHttpHandler({ factory });
98
+
99
+ app.post("/mcp/:environment", authenticate, (req, res) =>
100
+ mcp.handle(req, res, { principal: req.principal }),
101
+ );
102
+ ```
103
+
104
+ The principal is `{ environment, access, toolsets, destructive_allowed, key_id }`.
105
+ Authentication, rate limiting and audit hooks (`hooks.beforeCall`,
106
+ `hooks.afterCall`, `hooks.onDenied`) are the host's job.
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env node
2
+ /* eslint-disable no-console */
3
+ // stdio bridge to a Meterbox deployment's hosted MCP endpoint. Every check
4
+ // runs on the server; this process only relays messages and adds the key.
5
+ //
6
+ // METERBOX_BASE_URL your Meterbox host, e.g. https://meterbox.ai
7
+ // METERBOX_AGENT_KEY agent key (mb_agent_sandbox_... / mb_agent_production_...)
8
+ // --toolsets a,b optional: narrow the key's toolsets
9
+ const { runBridge } = require("../lib/bridge");
10
+
11
+ const HELP = `meterbox-mcp: connect a stdio MCP client to Meterbox.
12
+
13
+ Environment:
14
+ METERBOX_BASE_URL your Meterbox host, e.g. https://meterbox.ai
15
+ METERBOX_AGENT_KEY agent key from Settings > API keys (its prefix picks sandbox or production)
16
+
17
+ Options:
18
+ --toolsets a,b only expose these toolsets (narrows what the key allows)
19
+ --help show this help
20
+
21
+ Clients that support remote servers can connect to <METERBOX_BASE_URL>/mcp/<sandbox|production>
22
+ directly instead.`;
23
+
24
+ function parseArgs(argv) {
25
+ const out = {};
26
+ for (let i = 0; i < argv.length; i += 1) {
27
+ const a = argv[i];
28
+ if (a === "--help" || a === "-h") out.help = true;
29
+ else if (a === "--toolsets") out.toolsets = argv[(i += 1)];
30
+ else if (a.startsWith("--toolsets=")) out.toolsets = a.slice("--toolsets=".length);
31
+ else {
32
+ out.error = `unknown argument: ${a}`;
33
+ break;
34
+ }
35
+ }
36
+ return out;
37
+ }
38
+
39
+ const args = parseArgs(process.argv.slice(2));
40
+ if (args.help) {
41
+ console.log(HELP);
42
+ process.exit(0);
43
+ }
44
+ if (args.error) {
45
+ console.error(`meterbox-mcp: ${args.error}\n\n${HELP}`);
46
+ process.exit(2);
47
+ }
48
+
49
+ const baseUrl = process.env.METERBOX_BASE_URL;
50
+ const apiKey = process.env.METERBOX_AGENT_KEY;
51
+ if (!baseUrl || !apiKey) {
52
+ console.error(`meterbox-mcp: set METERBOX_BASE_URL and METERBOX_AGENT_KEY.\n\n${HELP}`);
53
+ process.exit(2);
54
+ }
55
+
56
+ const toolsets = args.toolsets
57
+ ? args.toolsets
58
+ .split(",")
59
+ .map((s) => s.trim())
60
+ .filter(Boolean)
61
+ : null;
62
+
63
+ runBridge({
64
+ baseUrl,
65
+ apiKey,
66
+ toolsets,
67
+ onError: (err) => console.error(`meterbox-mcp: ${err.message}`),
68
+ }).catch((err) => {
69
+ console.error(`meterbox-mcp: ${err.message}`);
70
+ process.exit(1);
71
+ });
package/index.js ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @meterbox/mcp — Meterbox's MCP server.
3
+ *
4
+ * The same code runs the hosted endpoint on a Meterbox deployment
5
+ * (`<host>/mcp/<sandbox|production>`) and ships as the `meterbox-mcp` stdio
6
+ * bridge to it. Seven meta-tools cover the whole /v1 API, filtered per
7
+ * caller by risk tier, access level and toolsets.
8
+ *
9
+ * Host-side surface:
10
+ * buildCatalog(spec) → reviewed operations (see lib/tiers.js)
11
+ * createServerFactory(options) → per-request McpServer factory
12
+ * createHttpHandler({ factory }) → { handle(req, res, { principal }), close }
13
+ * allowedTiers / authorize / narrowToolsets / visibleOperations → policy
14
+ *
15
+ * Client-side surface:
16
+ * runBridge(options) → stdio ↔ hosted endpoint relay
17
+ */
18
+
19
+ const { buildCatalog, listToolsets, toolsetSlug } = require("./lib/catalog");
20
+ const {
21
+ TOOL_TIER,
22
+ allowedTiers,
23
+ authorize,
24
+ narrowToolsets,
25
+ visibleOperations,
26
+ } = require("./lib/policy");
27
+ const { createServerFactory } = require("./lib/server");
28
+ const { createHttpHandler } = require("./lib/http");
29
+ const { redact } = require("./lib/redact");
30
+ const { TIERS } = require("./lib/tiers");
31
+ const { runBridge, environmentFromKey, mcpUrl } = require("./lib/bridge");
32
+
33
+ module.exports = {
34
+ buildCatalog,
35
+ listToolsets,
36
+ toolsetSlug,
37
+ TIERS,
38
+ TOOL_TIER,
39
+ allowedTiers,
40
+ authorize,
41
+ narrowToolsets,
42
+ visibleOperations,
43
+ createServerFactory,
44
+ createHttpHandler,
45
+ redact,
46
+ runBridge,
47
+ environmentFromKey,
48
+ mcpUrl,
49
+ };
package/lib/bridge.js ADDED
@@ -0,0 +1,124 @@
1
+ /**
2
+ * bridge.js — relay a local stdio MCP client to a Meterbox deployment's
3
+ * hosted MCP endpoint (`<base>/mcp/<environment>`).
4
+ *
5
+ * The bridge is a pipe, not a server: it forwards JSON-RPC messages both ways
6
+ * and adds the agent key as a Bearer token, so every access check, tool list
7
+ * and audit row stays on the server. That keeps one implementation of the
8
+ * policy for hosted clients and stdio-only clients alike, including a
9
+ * self-hosted deployment reachable only from inside its own network.
10
+ */
11
+
12
+ const { StdioServerTransport } = require("@modelcontextprotocol/server/stdio");
13
+ const { StreamableHTTPClientTransport } = require("@modelcontextprotocol/client");
14
+
15
+ const AGENT_KEY_RE = /^mb_agent_(sandbox|production)_/;
16
+ const ENVIRONMENTS = ["sandbox", "production"];
17
+
18
+ function environmentFromKey(key) {
19
+ const m = AGENT_KEY_RE.exec(key || "");
20
+ return m ? m[1] : null;
21
+ }
22
+
23
+ function mcpUrl(baseUrl, environment) {
24
+ return new URL(`${String(baseUrl).replace(/\/+$/, "")}/mcp/${environment}`);
25
+ }
26
+
27
+ function resolveEnvironment(apiKey, environment) {
28
+ const fromKey = environmentFromKey(apiKey);
29
+ if (environment && !ENVIRONMENTS.includes(environment)) {
30
+ throw new Error(`environment must be "sandbox" or "production", got "${environment}"`);
31
+ }
32
+ if (environment && fromKey && environment !== fromKey) {
33
+ throw new Error(`this is a ${fromKey} agent key, but environment is set to ${environment}`);
34
+ }
35
+ const env = environment || fromKey;
36
+ if (!env) throw new Error("use an agent key (mb_agent_sandbox_... or mb_agent_production_...)");
37
+ return env;
38
+ }
39
+
40
+ /**
41
+ * @param {object} opts
42
+ * @param {string} opts.baseUrl e.g. "https://meterbox.ai"
43
+ * @param {string} opts.apiKey agent key; its prefix picks the environment
44
+ * @param {string} [opts.environment] "sandbox" | "production" (must match the key)
45
+ * @param {string[]} [opts.toolsets] narrow the key's toolsets (never widens)
46
+ * @param {object} [opts.stdin] defaults to process.stdin
47
+ * @param {object} [opts.stdout] defaults to process.stdout
48
+ * @param {Function} [opts.fetch] custom fetch (tests)
49
+ * @param {Function} [opts.onError] called with transport errors
50
+ */
51
+ async function runBridge({
52
+ baseUrl,
53
+ apiKey,
54
+ environment,
55
+ toolsets,
56
+ stdin,
57
+ stdout,
58
+ fetch,
59
+ onError,
60
+ }) {
61
+ if (!baseUrl) throw new Error("baseUrl is required");
62
+ if (!apiKey) throw new Error("apiKey is required");
63
+ const env = resolveEnvironment(apiKey, environment);
64
+ const report = onError || (() => {});
65
+
66
+ const headers = { authorization: `Bearer ${apiKey}` };
67
+ if (toolsets && toolsets.length) headers["x-meterbox-toolsets"] = toolsets.join(",");
68
+ const remote = new StreamableHTTPClientTransport(mcpUrl(baseUrl, env), {
69
+ requestInit: { headers },
70
+ ...(fetch ? { fetch } : {}),
71
+ });
72
+ const local = new StdioServerTransport(stdin, stdout);
73
+
74
+ // id -> method, so the initialize response can pin the protocol version
75
+ // the HTTP transport stamps on every later request.
76
+ const inflight = new Map();
77
+
78
+ local.onmessage = async (msg) => {
79
+ const isRequest = msg && msg.method && msg.id !== undefined;
80
+ if (isRequest) inflight.set(msg.id, msg.method);
81
+ try {
82
+ await remote.send(msg);
83
+ } catch (err) {
84
+ report(err);
85
+ if (isRequest) {
86
+ inflight.delete(msg.id);
87
+ await local.send({
88
+ jsonrpc: "2.0",
89
+ id: msg.id,
90
+ error: { code: -32603, message: `Meterbox MCP endpoint error: ${err.message}` },
91
+ });
92
+ }
93
+ }
94
+ };
95
+
96
+ remote.onmessage = async (msg) => {
97
+ if (msg && msg.id !== undefined) {
98
+ const method = inflight.get(msg.id);
99
+ inflight.delete(msg.id);
100
+ if (method === "initialize" && msg.result && msg.result.protocolVersion) {
101
+ remote.setProtocolVersion(msg.result.protocolVersion);
102
+ }
103
+ }
104
+ await local.send(msg);
105
+ };
106
+ remote.onerror = report;
107
+ local.onerror = report;
108
+ local.onclose = () => {
109
+ remote.close().catch(report);
110
+ };
111
+
112
+ await remote.start();
113
+ await local.start();
114
+ return {
115
+ environment: env,
116
+ url: mcpUrl(baseUrl, env).toString(),
117
+ close: async () => {
118
+ await local.close();
119
+ await remote.close();
120
+ },
121
+ };
122
+ }
123
+
124
+ module.exports = { runBridge, environmentFromKey, mcpUrl, resolveEnvironment };
package/lib/catalog.js ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * catalog.js — the operations an MCP client can ever reach.
3
+ *
4
+ * Built from a deployment's OpenAPI spec by `@meterbox/ops`, annotated with
5
+ * each operation's risk tier (./tiers.js) and toolsets (its OpenAPI tags as
6
+ * slugs), with every "excluded" operation dropped. Operations the tier map
7
+ * doesn't know are excluded too, so a newer platform than this package never
8
+ * exposes an unreviewed endpoint.
9
+ */
10
+
11
+ const { buildOperationsFromSpec } = require("@meterbox/ops");
12
+ const { TIERS } = require("./tiers");
13
+
14
+ function toolsetSlug(tag) {
15
+ return String(tag)
16
+ .toLowerCase()
17
+ .replace(/[^a-z0-9]+/g, "-")
18
+ .replace(/^-+|-+$/g, "");
19
+ }
20
+
21
+ function buildCatalog(spec) {
22
+ return buildOperationsFromSpec(spec)
23
+ .map((op) => ({
24
+ ...op,
25
+ tier: TIERS[`${op.method} ${op.path}`] || "excluded",
26
+ toolsets: [...new Set((op.tags || []).map(toolsetSlug))],
27
+ }))
28
+ .filter((op) => op.tier !== "excluded");
29
+ }
30
+
31
+ function listToolsets(catalog) {
32
+ return [...new Set(catalog.flatMap((op) => op.toolsets))].sort();
33
+ }
34
+
35
+ module.exports = { buildCatalog, listToolsets, toolsetSlug };
package/lib/http.js ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * http.js — serve the MCP server over Streamable HTTP from Express or plain
3
+ * node:http, statelessly (no Mcp-Session-Id), for both protocol eras.
4
+ *
5
+ * The host does authentication, Origin checks and rate limiting first, then
6
+ * calls `handle(req, res, { principal })`. The principal is handed to the
7
+ * server factory directly; nothing from the request's own auth state (e.g.
8
+ * a session cookie's `req.auth`) is used.
9
+ */
10
+
11
+ const { createMcpHandler } = require("@modelcontextprotocol/server");
12
+ const { toNodeHandler } = require("@modelcontextprotocol/node");
13
+
14
+ function writeJsonRpcError(res, status, message) {
15
+ res.writeHead(status, { "content-type": "application/json" });
16
+ res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32600, message } }));
17
+ }
18
+
19
+ function createHttpHandler({ factory, onerror, maxRequestBodySize } = {}) {
20
+ if (typeof factory !== "function") throw new Error("meterbox-mcp: factory is required");
21
+ const mcp = createMcpHandler(factory, { onerror, maxRequestBodySize });
22
+ const adapterOptions = { onerror, maxRequestBodySize };
23
+
24
+ return {
25
+ async handle(req, res, { principal } = {}) {
26
+ if (!principal) throw new Error("meterbox-mcp: handle() needs a principal");
27
+ // A batch would let one HTTP request carry many tool calls past a
28
+ // per-request rate limit; no current MCP client sends them.
29
+ if (Array.isArray(req.body)) {
30
+ writeJsonRpcError(res, 400, "JSON-RPC batches are not supported.");
31
+ return;
32
+ }
33
+ const authInfo = {
34
+ token: "",
35
+ clientId: String(principal.key_id || "meterbox"),
36
+ scopes: [],
37
+ extra: { principal },
38
+ };
39
+ const node = toNodeHandler(
40
+ { fetch: (request, opts) => mcp.fetch(request, { ...opts, authInfo }) },
41
+ adapterOptions,
42
+ );
43
+ await node(req, res, req.body);
44
+ },
45
+ close: () => mcp.close(),
46
+ };
47
+ }
48
+
49
+ module.exports = { createHttpHandler };
package/lib/policy.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * policy.js — what a principal may do, enforced on every tools/list and
3
+ * tools/call. The principal comes from the host (e.g. a verified agent key):
4
+ *
5
+ * {
6
+ * environment, // "sandbox" | "production" (anything else = production)
7
+ * access, // "read_only" | "read_write"
8
+ * toolsets, // array of toolset slugs, or null for all
9
+ * destructive_allowed, // host-computed: sandbox with no live-mode money path
10
+ * key_id, // for attribution only
11
+ * }
12
+ *
13
+ * Rules:
14
+ * - read is always allowed.
15
+ * - create/update need read_write, and are sandbox-only unless the host opts
16
+ * into production writes.
17
+ * - destructive needs read_write + sandbox + destructive_allowed. It is
18
+ * never allowed in production.
19
+ * - every tool runs only operations of its own tier, so a read-only tool
20
+ * annotation can never front a write.
21
+ */
22
+
23
+ const TOOL_TIER = {
24
+ meterbox_read: "read",
25
+ meterbox_create: "create",
26
+ meterbox_update: "update",
27
+ meterbox_destructive: "destructive",
28
+ };
29
+ const TIER_TOOL = Object.fromEntries(Object.entries(TOOL_TIER).map(([tool, tier]) => [tier, tool]));
30
+
31
+ function isSandbox(principal) {
32
+ return principal && principal.environment === "sandbox";
33
+ }
34
+
35
+ function allowedTiers(principal, { productionWrites = false } = {}) {
36
+ const tiers = new Set(["read"]);
37
+ if (!principal || principal.access !== "read_write") return tiers;
38
+ if (isSandbox(principal) || productionWrites) {
39
+ tiers.add("create");
40
+ tiers.add("update");
41
+ }
42
+ if (isSandbox(principal) && principal.destructive_allowed === true) tiers.add("destructive");
43
+ return tiers;
44
+ }
45
+
46
+ function inToolsets(op, toolsets) {
47
+ if (!toolsets) return true;
48
+ return op.toolsets.some((t) => toolsets.includes(t));
49
+ }
50
+
51
+ function visibleOperations(catalog, principal, opts) {
52
+ const tiers = allowedTiers(principal, opts);
53
+ return catalog.filter((op) => tiers.has(op.tier) && inToolsets(op, principal.toolsets));
54
+ }
55
+
56
+ // Narrow a key's toolsets by a client-requested list. Never widens: a key
57
+ // limited to ["catalog"] asking for ["catalog", "billing"] gets ["catalog"].
58
+ function narrowToolsets(keyToolsets, requested) {
59
+ if (!requested || requested.length === 0) return keyToolsets || null;
60
+ if (!keyToolsets) return [...new Set(requested)];
61
+ return keyToolsets.filter((t) => requested.includes(t));
62
+ }
63
+
64
+ function tierDenial(principal, tier) {
65
+ if (!principal || principal.access !== "read_write") {
66
+ return "This key is read-only. Ask the account owner for a read-write sandbox key.";
67
+ }
68
+ if (!isSandbox(principal)) {
69
+ return tier === "destructive"
70
+ ? "Destructive and money-moving operations are blocked in production over MCP. Use the Meterbox dashboard, or a sandbox key."
71
+ : "Writes are disabled in production over MCP. Use the Meterbox dashboard, or a sandbox key.";
72
+ }
73
+ return "Destructive and money-moving operations are blocked in this sandbox because its billing provider is connected in live mode.";
74
+ }
75
+
76
+ function deny(code, message) {
77
+ return { allowed: false, code, message };
78
+ }
79
+
80
+ function authorize(principal, tool, op, opts) {
81
+ const tier = TOOL_TIER[tool];
82
+ if (!op) {
83
+ return deny(
84
+ "unknown_operation",
85
+ "Unknown operation. Use meterbox_search_operations to find one.",
86
+ );
87
+ }
88
+ if (!inToolsets(op, principal.toolsets)) {
89
+ return deny("outside_toolsets", `'${op.name}' is outside the toolsets this key allows.`);
90
+ }
91
+ if (op.tier !== tier) {
92
+ return deny(
93
+ "wrong_tool",
94
+ `'${op.name}' is a ${op.tier} operation. Call it with ${TIER_TOOL[op.tier]}.`,
95
+ );
96
+ }
97
+ if (!allowedTiers(principal, opts).has(op.tier)) {
98
+ return deny("tier_not_allowed", tierDenial(principal, op.tier));
99
+ }
100
+ return { allowed: true };
101
+ }
102
+
103
+ module.exports = {
104
+ TOOL_TIER,
105
+ TIER_TOOL,
106
+ allowedTiers,
107
+ authorize,
108
+ inToolsets,
109
+ narrowToolsets,
110
+ visibleOperations,
111
+ };
package/lib/redact.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * redact.js — strip secrets from anything headed back to a model.
3
+ *
4
+ * Operations that return credentials are excluded from the catalog, so this
5
+ * is the second line of defence: a secret-shaped key or value anywhere in a
6
+ * response is replaced before it reaches the tool result. Booleans, numbers
7
+ * and nulls are left alone (a `has_credentials: true` flag isn't a secret),
8
+ * and counts like `input_tokens` don't match the key pattern.
9
+ */
10
+
11
+ const REDACTED = "[REDACTED]";
12
+
13
+ const SECRET_KEY_RE =
14
+ /(^|_)(secret|secret_?key|password|passphrase|api_?key|access_?key|private_?key|signing_?key|client_?secret|access_?token|refresh_?token|id_?token|share_?token|session_?token|token|credentials?|authorization)$/i;
15
+
16
+ const SECRET_VALUE_RE =
17
+ /^(?:(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{8,}|whsec_[A-Za-z0-9]{8,}|mb_(?:live|agent_(?:sandbox|production))_[0-9a-f]{16,}|A(?:KIA|SIA)[0-9A-Z]{16}|sk-[A-Za-z0-9_-]{16,}|eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}|Bearer\s+\S{8,})/;
18
+
19
+ const MAX_DEPTH = 64;
20
+
21
+ function redact(value, depth = 0) {
22
+ if (depth > MAX_DEPTH) return REDACTED;
23
+ if (typeof value === "string") return SECRET_VALUE_RE.test(value) ? REDACTED : value;
24
+ if (Array.isArray(value)) return value.map((v) => redact(v, depth + 1));
25
+ if (!value || typeof value !== "object") return value;
26
+ const out = {};
27
+ for (const [k, v] of Object.entries(value)) {
28
+ const sensitive =
29
+ SECRET_KEY_RE.test(k) &&
30
+ ((typeof v === "string" && v !== "") || (v && typeof v === "object"));
31
+ out[k] = sensitive ? REDACTED : redact(v, depth + 1);
32
+ }
33
+ return out;
34
+ }
35
+
36
+ module.exports = { redact, REDACTED };
package/lib/result.js ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * result.js — shape tool results for a model: a small JSON envelope, secrets
3
+ * redacted, size capped.
4
+ *
5
+ * The cap keeps results well under Claude Code's 25k-token default. When a
6
+ * response is too big, the largest list in it is trimmed (so the JSON stays
7
+ * parseable and the model is told how many items it's missing) before
8
+ * falling back to cutting the text.
9
+ */
10
+
11
+ const { redact } = require("./redact");
12
+
13
+ const MAX_RESULT_CHARS = 25_000;
14
+ const TRUNCATION_HINT =
15
+ "Narrow the request (limit, cursor, filters, or a single id) to see the rest.";
16
+
17
+ function textResult(text, isError = false) {
18
+ return isError
19
+ ? { isError: true, content: [{ type: "text", text }] }
20
+ : { content: [{ type: "text", text }] };
21
+ }
22
+
23
+ // Find the largest array at the top of `data` or one level below it.
24
+ function largestList(data) {
25
+ if (Array.isArray(data)) return { key: null, list: data };
26
+ if (!data || typeof data !== "object") return null;
27
+ let best = null;
28
+ for (const [key, v] of Object.entries(data)) {
29
+ if (
30
+ Array.isArray(v) &&
31
+ (!best || JSON.stringify(v).length > JSON.stringify(best.list).length)
32
+ ) {
33
+ best = { key, list: v };
34
+ }
35
+ }
36
+ return best;
37
+ }
38
+
39
+ function withList(envelope, found, items) {
40
+ const truncated = { kept: items.length, total: found.list.length, hint: TRUNCATION_HINT };
41
+ if (found.key === null) return { ...envelope, data: items, truncated };
42
+ return {
43
+ ...envelope,
44
+ data: { ...envelope.data, [found.key]: items },
45
+ truncated: { field: found.key, ...truncated },
46
+ };
47
+ }
48
+
49
+ function shrinkList(envelope, max) {
50
+ const found = largestList(envelope.data);
51
+ if (!found || found.list.length === 0) return null;
52
+ let lo = 0;
53
+ let hi = found.list.length;
54
+ while (lo < hi) {
55
+ const mid = Math.ceil((lo + hi) / 2);
56
+ if (JSON.stringify(withList(envelope, found, found.list.slice(0, mid))).length <= max) lo = mid;
57
+ else hi = mid - 1;
58
+ }
59
+ const text = JSON.stringify(withList(envelope, found, found.list.slice(0, lo)));
60
+ return text.length <= max ? text : null;
61
+ }
62
+
63
+ function formatEnvelope(envelope, max = MAX_RESULT_CHARS) {
64
+ const safe = redact(envelope);
65
+ const pretty = JSON.stringify(safe, null, 2);
66
+ if (pretty.length <= max) return pretty;
67
+ const compact = JSON.stringify(safe);
68
+ if (compact.length <= max) return compact;
69
+ const shrunk = shrinkList(safe, max);
70
+ if (shrunk) return shrunk;
71
+ return `${compact.slice(0, max)}\n--- TRUNCATED: response was ${compact.length} characters. ${TRUNCATION_HINT} ---`;
72
+ }
73
+
74
+ module.exports = { formatEnvelope, textResult, MAX_RESULT_CHARS };