@pipeworx/mcp-global-peace-index 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@ Annual country peacefulness score and rank — country-risk context to pair
4
4
  with event/news data, so a spike of conflict or violence news for a country
5
5
  can be read against its standing peacefulness level.
6
6
 
7
- Part of [Pipeworx](https://pipeworx.io) — an MCP gateway connecting AI agents to 1831+ live data sources. This is an independent, unofficial integration — not affiliated with, endorsed by, or published by the upstream provider.
7
+ Part of [Pipeworx](https://pipeworx.io) — an MCP gateway connecting AI agents to 1856+ live data sources. This is an independent, unofficial integration — not affiliated with, endorsed by, or published by the upstream provider.
8
8
 
9
9
  ## Tools
10
10
 
@@ -97,7 +97,7 @@ directly, instead of just this one's:
97
97
  }
98
98
  ```
99
99
 
100
- Both URLs reach the same gateway and the same 1831+ data sources. The
100
+ Both URLs reach the same gateway and the same 1856+ data sources. The
101
101
  only difference is which pack's tools are listed **directly**; `ask_pipeworx`
102
102
  reaches all of them from either one.
103
103
 
@@ -111,10 +111,12 @@ curl -X POST https://gateway.pipeworx.io/v1/tools/gpi_country_score \
111
111
 
112
112
  No account needed for the first calls. Inspect any tool: `GET https://gateway.pipeworx.io/v1/tools/gpi_country_score`. Find one: `POST https://gateway.pipeworx.io/v1/tools/search_packs` with `{"query":"..."}`.
113
113
 
114
- ## Standalone (no gateway account)
114
+ ## Run it from npm
115
115
 
116
- This package also runs as a local stdio MCP server — no Pipeworx account, no
117
- gateway round-trip:
116
+ `@pipeworx/mcp-global-peace-index` is a local stdio bridge to the Pipeworx gateway: your MCP client
117
+ starts it with `npx`, and it forwards every call to the same
118
+ `https://gateway.pipeworx.io/global-peace-index/mcp` endpoint shown above. It needs network access;
119
+ there is no offline mode.
118
120
 
119
121
  ```json
120
122
  {
@@ -127,15 +129,18 @@ gateway round-trip:
127
129
  }
128
130
  ```
129
131
 
130
- Or run it directly to confirm it starts:
132
+ Without a key it calls anonymously, capped at 50 calls a day. A free account
133
+ raises that to 200 a day: get a key at https://pipeworx.io/signup and add
134
+ `"env": { "PIPEWORX_API_KEY": "<your key>" }` to the server entry.
135
+ The key is sent as a Bearer token, the same way a hosted connection sends it,
136
+ so calls are metered and billed exactly as they are there.
131
137
 
132
- ```bash
133
- npx -y @pipeworx/mcp-global-peace-index
134
- ```
138
+ It lists **only** this pack's tools by default. Set `PIPEWORX_META_TOOLS=1` to
139
+ also list `ask_pipeworx` and the other gateway-wide tools.
135
140
 
136
- It speaks MCP over stdin/stdout and answers `initialize`/`tools/list`/`tools/call`
137
- for **only** this pack's tools — none of the shared meta-tools the gateway
138
- connection above adds. Same source, same tools, no ask_pipeworx routing.
141
+ Behind an HTTPS proxy: Node's built-in `fetch` does not read `HTTPS_PROXY` by
142
+ default. Newer Node releases honour it when `NODE_USE_ENV_PROXY=1` is set; check
143
+ your Node version's documentation.
139
144
 
140
145
  ## Using with ask_pipeworx
141
146
 
package/bin/cli.js CHANGED
@@ -1,17 +1,61 @@
1
1
  #!/usr/bin/env node
2
+ // Entry point for `npx @pipeworx/mcp-<slug>` in gateway mode (bin/cli.js).
2
3
  //
3
- // Entry point for `npx @pipeworx/mcp-<slug>`.
4
+ // A stdio MCP server that relays every message to the Pipeworx gateway's
5
+ // /<slug>/mcp endpoint -- fleet #3759, docs/standalone-via-gateway-plan.md.
6
+ // It carries no pack code and has no local mode. The relay itself lives in
7
+ // ../lib/index.js (copied from scripts/templates/standalone-gateway-lib.js);
8
+ // this file only owns stdin/stdout.
4
9
  //
5
- // Packs ship as raw TypeScript (no build step — see publish-pack.sh for why:
6
- // tsx sidesteps every extensionless-import / bare-JSON-import edge case a
7
- // per-pack tsc build would have to solve one pack at a time). This file
8
- // registers tsx's ESM loader programmatically, then hands off to src/server.ts,
9
- // which wraps the pack's {tools, callTool} export in a stdio MCP server.
10
+ // Copied VERBATIM into every gateway-mode package by scripts/publish-pack.sh.
11
+ // Edit scripts/templates/standalone-gateway-cli.js in the monorepo, never a
12
+ // per-pack copy. Zero dependencies, Node 18+.
10
13
  //
11
- // Copied verbatim into every published pack repo by scripts/publish-pack.sh —
12
- // edit this file, not a per-pack copy.
13
- import { register } from 'tsx/esm/api';
14
+ // stdout carries newline-delimited JSON-RPC and nothing else; every diagnostic
15
+ // goes to stderr, because a single stray line on stdout breaks the host's
16
+ // parser.
17
+ import { createInterface } from 'node:readline';
18
+ import { relay, bridgeConfig } from '../lib/index.js';
14
19
 
15
- register();
20
+ const cfg = bridgeConfig();
21
+ const warn = (line) => process.stderr.write(`${line}\n`);
22
+ const write = (msg) => { if (msg) process.stdout.write(`${JSON.stringify(msg)}\n`); };
16
23
 
17
- await import('../src/server.ts');
24
+ const pending = new Set();
25
+ function track(p) {
26
+ pending.add(p);
27
+ p.finally(() => pending.delete(p));
28
+ }
29
+
30
+ async function handleLine(line) {
31
+ const text = line.trim();
32
+ if (!text) return;
33
+ let message;
34
+ try {
35
+ message = JSON.parse(text);
36
+ } catch {
37
+ write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
38
+ return;
39
+ }
40
+ // A JSON-RPC batch: relay each member, answer with the non-notification replies.
41
+ if (Array.isArray(message)) {
42
+ const replies = (await Promise.all(message.map((m) => relay(m, { cfg, warn })))).filter(Boolean);
43
+ if (replies.length) write(replies);
44
+ return;
45
+ }
46
+ write(await relay(message, { cfg, warn }));
47
+ }
48
+
49
+ // Requests are handled concurrently and answered as they finish: JSON-RPC ids
50
+ // let the host match them, and a slow tool call must not hold up a ping.
51
+ const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
52
+ rl.on('line', (line) => {
53
+ track(handleLine(line).catch((err) => warn(`pipeworx-standalone: ${err && err.stack ? err.stack : err}`)));
54
+ });
55
+ rl.on('close', async () => {
56
+ // stdin closed: finish what is in flight, then exit.
57
+ while (pending.size) await Promise.allSettled([...pending]);
58
+ // Exit only once stdout has flushed: on a pipe that is not synchronous
59
+ // everywhere, and a bare exit can drop the last reply.
60
+ process.stdout.write('', () => process.exit(0));
61
+ });
package/lib/index.js ADDED
@@ -0,0 +1,333 @@
1
+ // @pipeworx/mcp-<slug> -- library half of the gateway bridge (lib/index.js).
2
+ //
3
+ // Copied VERBATIM into every gateway-mode pack package by scripts/publish-pack.sh
4
+ // (fleet #3759, docs/standalone-via-gateway-plan.md section 1). There is no
5
+ // per-pack templating: the slug and version are read from this package's own
6
+ // package.json (`pipeworx.slug`, `version`) at load time, so the same bytes
7
+ // ship in every package and the source hash can cover them once. Edit this
8
+ // file in the monorepo (scripts/templates/standalone-gateway-lib.js), never a
9
+ // per-pack copy.
10
+ //
11
+ // What it is: a relay. Every JSON-RPC message goes to
12
+ // ${PIPEWORX_GATEWAY_URL:-https://gateway.pipeworx.io}/<slug>/mcp, the same
13
+ // endpoint a hosted MCP client uses, so tiers, rate limits and credits apply
14
+ // exactly as they do there. There is no local mode: the pack's code is not in
15
+ // this package.
16
+ //
17
+ // Zero dependencies, plain ESM, Node 18+ (global fetch). Nothing here writes
18
+ // to stdout -- bin/cli.js owns stdout and it carries JSON-RPC only.
19
+ //
20
+ // Environment:
21
+ // PIPEWORX_API_KEY sent as `Authorization: Bearer <key>`. Never as
22
+ // X-API-Key: the gateway reads a pwx_ key sent that way
23
+ // as an unvalidated BYO string with no account.
24
+ // PIPEWORX_GATEWAY_URL gateway base URL (no path), default the public gateway.
25
+ // PIPEWORX_META_TOOLS=1 list the gateway-wide tools (ask_pipeworx, ...) too.
26
+ // PIPEWORX_TIMEOUT_MS per-request timeout, default 120000.
27
+
28
+ import { readFileSync } from 'node:fs';
29
+
30
+ const readJson = (rel) => JSON.parse(readFileSync(new URL(rel, import.meta.url), 'utf8'));
31
+
32
+ const PKG = readJson('../package.json');
33
+ export const SLUG = PKG.pipeworx && PKG.pipeworx.slug;
34
+ if (typeof SLUG !== 'string' || !/^[a-z0-9][a-z0-9_-]*$/.test(SLUG)) {
35
+ throw new Error(`${PKG.name}: package.json carries no valid pipeworx.slug -- this package was built wrong`);
36
+ }
37
+ /**
38
+ * The pack's slug on the GATEWAY: the /<slug>/mcp route and the `_meta.pack`
39
+ * every listed tool carries. Usually the same as `slug` (the npm/directory
40
+ * name), but 14 packs differ -- `hex-pm` is `hex_pm` on the gateway -- and
41
+ * filtering tools/list on the npm slug would match none of their tools
42
+ * (fleet #3761). publish-pack.sh stamps it from the gateway manifest.
43
+ */
44
+ export const GATEWAY_SLUG = (PKG.pipeworx && PKG.pipeworx.gatewaySlug) || SLUG;
45
+ if (typeof GATEWAY_SLUG !== 'string' || !/^[a-z0-9][a-z0-9_-]*$/.test(GATEWAY_SLUG)) {
46
+ throw new Error(`${PKG.name}: package.json carries an invalid pipeworx.gatewaySlug -- this package was built wrong`);
47
+ }
48
+ export const PACKAGE_NAME = PKG.name;
49
+ export const VERSION = PKG.version;
50
+
51
+ /** The pack's own tool definitions at publish time (the offline tools/list answer). */
52
+ export const tools = readJson('../tools.json');
53
+
54
+ const DEFAULT_GATEWAY = 'https://gateway.pipeworx.io';
55
+ const DEFAULT_TIMEOUT_MS = 120_000;
56
+ const SIGNUP_URL = 'https://pipeworx.io/signup';
57
+ const VIA = '(via pipeworx-standalone)';
58
+
59
+ /** Resolve the bridge's settings. Exported for the tests and for callTool. */
60
+ export function bridgeConfig(env = process.env, overrides = {}) {
61
+ const base = String(overrides.gatewayUrl || env.PIPEWORX_GATEWAY_URL || DEFAULT_GATEWAY).trim().replace(/\/+$/, '');
62
+ const apiKey = String(overrides.apiKey ?? env.PIPEWORX_API_KEY ?? '').trim();
63
+ const t = Number(overrides.timeoutMs ?? env.PIPEWORX_TIMEOUT_MS);
64
+ return {
65
+ endpoint: `${base}/${GATEWAY_SLUG}/mcp`,
66
+ apiKey,
67
+ timeoutMs: Number.isFinite(t) && t > 0 ? t : DEFAULT_TIMEOUT_MS,
68
+ metaTools: (overrides.metaTools ?? env.PIPEWORX_META_TOOLS) === '1' || overrides.metaTools === true,
69
+ };
70
+ }
71
+
72
+ function requestHeaders(cfg) {
73
+ const h = {
74
+ 'Content-Type': 'application/json',
75
+ Accept: 'application/json',
76
+ // Stable per package version: the gateway remembers a client's name by
77
+ // identifier + User-Agent (workers/gateway/src/client-identity.ts).
78
+ 'User-Agent': `pipeworx-standalone/${VERSION} (${PACKAGE_NAME})`,
79
+ // Analytics label only (blob11 = 'standalone'). It never changes tier,
80
+ // limits or price -- anyone can send it.
81
+ 'X-Pipeworx-Surface': 'standalone',
82
+ };
83
+ if (cfg.apiKey) h.Authorization = `Bearer ${cfg.apiKey}`;
84
+ return h;
85
+ }
86
+
87
+ /** Parse a gateway body: JSON, or the last JSON `data:` frame of an SSE stream. */
88
+ function parseBody(text, contentType) {
89
+ if (/text\/event-stream/i.test(contentType || '')) {
90
+ let last = null;
91
+ for (const line of text.split(/\r?\n/)) {
92
+ if (!line.startsWith('data:')) continue;
93
+ try { last = JSON.parse(line.slice(5).trim()); } catch { /* keep-alive or partial frame */ }
94
+ }
95
+ return last;
96
+ }
97
+ try { return JSON.parse(text); } catch { return null; }
98
+ }
99
+
100
+ /**
101
+ * POST one JSON-RPC message. Never throws: the outcome is one of
102
+ * { kind: 'http', status, headers, body, text } the gateway answered
103
+ * { kind: 'network', detail } DNS, TLS, refused, reset
104
+ * { kind: 'timeout' } no answer in cfg.timeoutMs
105
+ */
106
+ export async function postToGateway(message, cfg) {
107
+ const ac = new AbortController();
108
+ const timer = setTimeout(() => ac.abort(), cfg.timeoutMs);
109
+ try {
110
+ const res = await fetch(cfg.endpoint, {
111
+ method: 'POST',
112
+ headers: requestHeaders(cfg),
113
+ body: JSON.stringify(message),
114
+ signal: ac.signal,
115
+ });
116
+ const text = await res.text();
117
+ return { kind: 'http', status: res.status, headers: res.headers, body: parseBody(text, res.headers.get('content-type')), text };
118
+ } catch (err) {
119
+ if (ac.signal.aborted || (err && (err.name === 'AbortError' || err.name === 'TimeoutError'))) return { kind: 'timeout' };
120
+ const cause = err && err.cause;
121
+ const detail = (cause && (cause.code || cause.message)) || (err && err.message) || String(err);
122
+ return { kind: 'network', detail };
123
+ } finally {
124
+ clearTimeout(timer);
125
+ }
126
+ }
127
+
128
+ // ── The key-not-accepted warning (one per process) ──────────────────
129
+
130
+ let warnedKeyIgnored = false;
131
+ const KEY_IGNORED = 'PIPEWORX_API_KEY was not accepted, calling anonymously.';
132
+
133
+ /** True when a key was sent but the gateway still served the call as anonymous. */
134
+ function keyIgnored(out, cfg) {
135
+ return !!cfg.apiKey && out.kind === 'http' && (out.headers.get('x-ratelimit-tier') || '').toLowerCase() === 'anonymous';
136
+ }
137
+
138
+ function noteTier(out, cfg, warn) {
139
+ if (!keyIgnored(out, cfg) || warnedKeyIgnored) return;
140
+ warnedKeyIgnored = true;
141
+ warn(`${PACKAGE_NAME}: ${KEY_IGNORED} Check the key at ${SIGNUP_URL}.`);
142
+ }
143
+
144
+ /** Test hook: forget that the warning was printed. */
145
+ export function _resetWarnings() { warnedKeyIgnored = false; }
146
+
147
+ // ── Results the host shows to the model ─────────────────────────────
148
+
149
+ function errorResult(text, detail) {
150
+ const result = { content: [{ type: 'text', text }], isError: true };
151
+ if (detail) result._meta = { pipeworx_standalone: detail };
152
+ return result;
153
+ }
154
+
155
+ const rpcResult = (id, result) => ({ jsonrpc: '2.0', id, result });
156
+ const rpcError = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
157
+
158
+ function firstLine(text) {
159
+ const line = String(text || '').split(/\r?\n/).map((l) => l.trim()).find(Boolean) || '(empty body)';
160
+ return line.length > 200 ? `${line.slice(0, 200)}...` : line;
161
+ }
162
+
163
+ function unreachableText(cfg, out) {
164
+ if (out.kind === 'timeout') {
165
+ return `The Pipeworx gateway at ${cfg.endpoint} did not answer within ${Math.round(cfg.timeoutMs / 1000)}s, so this call timed out. `
166
+ + `${PACKAGE_NAME} forwards every call to the Pipeworx gateway and has no local mode. Try again; a call that keeps timing out is worth reporting.`;
167
+ }
168
+ return `Could not reach the Pipeworx gateway at ${cfg.endpoint} (${out.detail}). `
169
+ + `${PACKAGE_NAME} forwards every call to the Pipeworx gateway and has no local mode, so it needs network access.`;
170
+ }
171
+
172
+ function isAuthRequired(body) {
173
+ return !!body && (body.error_code === 'authentication_required'
174
+ || (body.error && body.error.data && body.error.data.reason === 'authentication_required'));
175
+ }
176
+
177
+ /** Map a tools/call outcome to the JSON-RPC response the host gets. */
178
+ function toolsCallResponse(id, out, cfg) {
179
+ if (out.kind !== 'http') return rpcResult(id, errorResult(unreachableText(cfg, out), { reason: out.kind }));
180
+ const { status, body } = out;
181
+
182
+ // Anonymous daily cap: the gateway answers 401 with a JSON-RPC error whose
183
+ // message is the offer. Hosts often swallow protocol errors, so hand it over
184
+ // as a tool result the model actually reads.
185
+ if (status === 401 && isAuthRequired(body)) {
186
+ const data = (body.error && body.error.data) || {};
187
+ const parts = [body.error && body.error.message ? body.error.message : 'The anonymous daily allowance is used up.'];
188
+ if (data.resets_at) parts.push(`The anonymous allowance resets at ${data.resets_at}.`);
189
+ parts.push(cfg.apiKey
190
+ ? `${KEY_IGNORED} Check the key, or get a free one at ${SIGNUP_URL}.`
191
+ : `To keep going now, set PIPEWORX_API_KEY in this MCP server's environment; a free key is at ${SIGNUP_URL}.`);
192
+ return rpcResult(id, errorResult(parts.join('\n\n'), { status, reason: 'authentication_required', resets_at: data.resets_at ?? null }));
193
+ }
194
+
195
+ // A keyed tier over its cap: today the gateway answers 429 with a RESULT
196
+ // that has no isError, which reads as a success (fleet #3760). Mark it.
197
+ if (status === 429 && body && body.result && typeof body.result === 'object') {
198
+ const result = { ...body.result, isError: true };
199
+ if (cfg.apiKey && keyIgnored(out, cfg)) {
200
+ result.content = [...(Array.isArray(result.content) ? result.content : []), { type: 'text', text: KEY_IGNORED }];
201
+ }
202
+ return rpcResult(id, result);
203
+ }
204
+ if ((status === 401 || status === 429) && body && body.error) {
205
+ const extra = keyIgnored(out, cfg) ? ` ${KEY_IGNORED}` : '';
206
+ return rpcResult(id, errorResult(`${body.error.message || `HTTP ${status}`}${extra}`, { status }));
207
+ }
208
+
209
+ // A real JSON-RPC answer (result or protocol error): relay it verbatim,
210
+ // structuredContent and _meta (cost, tier, provenance) included.
211
+ if (body && body.jsonrpc === '2.0' && (body.result !== undefined || body.error !== undefined) && status < 500) {
212
+ return { ...body, id };
213
+ }
214
+
215
+ // 5xx, an HTML edge page, or anything else that is not JSON-RPC.
216
+ return rpcResult(id, errorResult(`The Pipeworx gateway returned HTTP ${status}: ${firstLine(out.text)}`, { status }));
217
+ }
218
+
219
+ function localInitialize(params) {
220
+ return {
221
+ protocolVersion: (params && params.protocolVersion) || '2025-06-18',
222
+ capabilities: { tools: {} },
223
+ serverInfo: { name: PACKAGE_NAME, version: VERSION },
224
+ };
225
+ }
226
+
227
+ const scopedInstructions = () =>
228
+ `${PACKAGE_NAME} forwards to the Pipeworx gateway and lists only the ${SLUG} pack's tools. `
229
+ + 'Set PIPEWORX_META_TOOLS=1 to also list ask_pipeworx and the other gateway-wide tools.';
230
+
231
+ /** `<host name> (via pipeworx-standalone)`. The slug stays OUT of the name: the
232
+ * gateway's scanner-name check substring-matches words like poll/watch/index. */
233
+ export function bridgedClientName(name) {
234
+ const n = typeof name === 'string' && name.trim() ? name.trim() : 'unknown';
235
+ return n.includes(VIA) ? n : `${n} ${VIA}`;
236
+ }
237
+
238
+ /**
239
+ * Relay one JSON-RPC message to the gateway and return the response to write
240
+ * back, or null for a notification. Never throws.
241
+ *
242
+ * @param {object} message a parsed JSON-RPC request or notification
243
+ * @param {{cfg?: object, warn?: (line: string) => void}} [opts]
244
+ */
245
+ export async function relay(message, opts = {}) {
246
+ const cfg = opts.cfg || bridgeConfig();
247
+ const warn = opts.warn || ((line) => process.stderr.write(`${line}\n`));
248
+ if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0' || typeof message.method !== 'string') {
249
+ const id = message && typeof message === 'object' && 'id' in message ? message.id : null;
250
+ return rpcError(id ?? null, -32600, 'Invalid Request');
251
+ }
252
+ const isNotification = !('id' in message) || message.id === undefined;
253
+ const id = message.id;
254
+
255
+ if (isNotification) {
256
+ const out = await postToGateway(message, cfg);
257
+ if (out.kind !== 'http') warn(`${PACKAGE_NAME}: notification ${message.method} not delivered: ${unreachableText(cfg, out)}`);
258
+ return null;
259
+ }
260
+
261
+ if (message.method === 'initialize') {
262
+ const params = { ...(message.params || {}) };
263
+ params.clientInfo = { ...(params.clientInfo || {}), name: bridgedClientName(params.clientInfo && params.clientInfo.name) };
264
+ if (!params.clientInfo.version) params.clientInfo.version = '0';
265
+ const out = await postToGateway({ ...message, params }, cfg);
266
+ noteTier(out, cfg, warn);
267
+ if (out.kind === 'http' && out.body && out.body.result && typeof out.body.result === 'object') {
268
+ const result = { ...out.body.result, serverInfo: { name: PACKAGE_NAME, version: VERSION } };
269
+ if (!cfg.metaTools) result.instructions = scopedInstructions();
270
+ return rpcResult(id, result);
271
+ }
272
+ // The host must still start: answer locally and let the calls report the
273
+ // gateway problem when they happen.
274
+ warn(`${PACKAGE_NAME}: initialize answered locally -- ${out.kind === 'http' ? `gateway HTTP ${out.status}` : unreachableText(cfg, out)}`);
275
+ return rpcResult(id, { ...localInitialize(message.params), instructions: scopedInstructions() });
276
+ }
277
+
278
+ if (message.method === 'tools/list') {
279
+ const out = await postToGateway(message, cfg);
280
+ noteTier(out, cfg, warn);
281
+ const listed = out.kind === 'http' && out.body && out.body.result && Array.isArray(out.body.result.tools)
282
+ ? out.body.result : null;
283
+ if (listed) {
284
+ if (cfg.metaTools) return rpcResult(id, listed);
285
+ const own = listed.tools.filter((t) => t && t._meta && (t._meta.pack === GATEWAY_SLUG || t._meta.pack === SLUG));
286
+ if (own.length > 0) return rpcResult(id, { ...listed, tools: own });
287
+ warn(`${PACKAGE_NAME}: the gateway listed no ${SLUG} tools; serving the tool list bundled with this package`);
288
+ } else {
289
+ warn(`${PACKAGE_NAME}: tools/list served from the snapshot bundled with this package -- ${out.kind === 'http' ? `gateway HTTP ${out.status}` : unreachableText(cfg, out)}`);
290
+ }
291
+ return rpcResult(id, { tools });
292
+ }
293
+
294
+ if (message.method === 'tools/call') {
295
+ const out = await postToGateway(message, cfg);
296
+ noteTier(out, cfg, warn);
297
+ return toolsCallResponse(id, out, cfg);
298
+ }
299
+
300
+ // Everything else (ping, resources/*, prompts/*, ...): relay as-is.
301
+ const out = await postToGateway(message, cfg);
302
+ noteTier(out, cfg, warn);
303
+ if (out.kind === 'http' && out.body && out.body.jsonrpc === '2.0') return { ...out.body, id };
304
+ if (message.method === 'ping') return rpcResult(id, {});
305
+ return rpcError(id, -32603, out.kind === 'http'
306
+ ? `The Pipeworx gateway returned HTTP ${out.status}: ${firstLine(out.text)}`
307
+ : unreachableText(cfg, out));
308
+ }
309
+
310
+ /**
311
+ * Call one of this pack's tools through the gateway -- the `{tools, callTool}`
312
+ * shape earlier versions of this package exported. Resolves with the tool's
313
+ * structured result; rejects with the gateway's message on any error.
314
+ *
315
+ * @param {string} name
316
+ * @param {Record<string, unknown>} [args]
317
+ * @param {{apiKey?: string, gatewayUrl?: string, timeoutMs?: number}} [opts]
318
+ * apiKey defaults to process.env.PIPEWORX_API_KEY.
319
+ */
320
+ export async function callTool(name, args = {}, opts = {}) {
321
+ const cfg = bridgeConfig(process.env, opts);
322
+ const res = await relay({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, { cfg });
323
+ if (res.error) throw new Error(res.error.message);
324
+ const result = res.result || {};
325
+ const text = Array.isArray(result.content)
326
+ ? result.content.filter((c) => c && c.type === 'text').map((c) => c.text).join('\n')
327
+ : '';
328
+ if (result.isError) throw new Error(text || `${name} failed`);
329
+ if (result.structuredContent !== undefined) return result.structuredContent;
330
+ try { return JSON.parse(text); } catch { return text; }
331
+ }
332
+
333
+ export default { tools, callTool };
package/package.json CHANGED
@@ -1,32 +1,33 @@
1
1
  {
2
2
  "name": "@pipeworx/mcp-global-peace-index",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Global Peace Index — annual country peacefulness score and rank, for country-risk context alongside event/news data (fleet #3276).",
5
5
  "type": "module",
6
- "main": "src/index.ts",
7
- "types": "src/index.ts",
6
+ "main": "lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./tools.json": "./tools.json",
10
+ "./package.json": "./package.json"
11
+ },
8
12
  "bin": {
9
13
  "mcp-global-peace-index": "bin/cli.js"
10
14
  },
15
+ "files": ["bin/", "lib/", "tools.json", "server.json"],
16
+ "engines": {
17
+ "node": ">=18"
18
+ },
11
19
  "keywords": ["mcp", "mcp-server", "model-context-protocol", "pipeworx", "global-peace-index"],
12
20
  "license": "MIT",
13
21
  "repository": {
14
22
  "type": "git",
15
23
  "url": "git+https://github.com/pipeworx-io/mcp-global-peace-index.git"
16
24
  },
17
- "scripts": {
18
- "typecheck": "tsc --noEmit"
19
- },
20
- "dependencies": {
21
- "@modelcontextprotocol/sdk": "^1.30.0",
22
- "tsx": "^4.19.0"
23
- },
24
- "devDependencies": {
25
- "typescript": "^5.9.3",
26
- "@cloudflare/workers-types": "^4.20260405.1"
27
- },
25
+ "mcpName": "io.github.pipeworx-io/global-peace-index",
28
26
  "pipeworx": {
29
- "sourceHash": "v1-c6c0cb1710288747fca580116c79f3c7db5938177b515d0f6f0a7e822e4fc02b",
30
- "sourceCommit": "514e3efb42b8d81082c07e01d3ae7654bbf91f52"
27
+ "mode": "gateway",
28
+ "slug": "global-peace-index",
29
+ "gatewaySlug": "global-peace-index",
30
+ "sourceHash": "v1-a25e8cb0aed72c1bf1dc39bb0a91f6ef1f3f055417b0cd2c375c3102307486d4",
31
+ "sourceCommit": "4844029e402d6bd2fe735add8abf6d46735f8ed5"
31
32
  }
32
33
  }
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "io.github.pipeworx-io/global-peace-index",
4
4
  "title": "Global Peace Index",
5
5
  "description": "Global Peace Index — annual country peacefulness score and rank, for country-risk context…",
6
- "version": "0.1.0",
6
+ "version": "0.2.0",
7
7
  "websiteUrl": "https://pipeworx.io/packs/global-peace-index",
8
8
  "repository": {
9
9
  "url": "https://github.com/pipeworx-io/mcp-global-peace-index",
package/tools.json ADDED
@@ -0,0 +1,39 @@
1
+ [
2
+ {
3
+ "name": "gpi_country_score",
4
+ "description": "Global Peace Index score and rank for ONE country — a country peacefulness measure (societal safety, ongoing conflict, and militarisation indicators rolled into one score; LOWER = more peaceful). Published annually by the Institute for Economics & Peace. PREFER for \"how peaceful is <country>\", \"<country> global peace index\", \"peace ranking for <country>\", or as background context on a country before/alongside news-event data (complements gdelt). Pass a country name (e.g. \"Iceland\", \"Russia\", \"United States\" — common aliases like \"USA\"/\"DRC\" are accepted).",
5
+ "inputSchema": {
6
+ "type": "object",
7
+ "properties": {
8
+ "country": {
9
+ "type": "string",
10
+ "description": "Country name (e.g. \"Ukraine\", \"Japan\", \"USA\")."
11
+ }
12
+ },
13
+ "required": [
14
+ "country"
15
+ ]
16
+ }
17
+ },
18
+ {
19
+ "name": "gpi_ranking",
20
+ "description": "Rank countries by Global Peace Index score — the N most peaceful or N least peaceful countries in one call, with rank and score. PREFER for \"most peaceful countries\", \"least peaceful/most dangerous countries\", \"top 10 most peaceful nations\", \"which countries have the worst peace ranking\". direction defaults to \"most_peaceful\".",
21
+ "inputSchema": {
22
+ "type": "object",
23
+ "properties": {
24
+ "limit": {
25
+ "type": "number",
26
+ "description": "How many countries to return (default 10, max 50)."
27
+ },
28
+ "direction": {
29
+ "type": "string",
30
+ "enum": [
31
+ "most_peaceful",
32
+ "least_peaceful"
33
+ ],
34
+ "description": "Which end of the ranking to return. Default \"most_peaceful\"."
35
+ }
36
+ }
37
+ }
38
+ }
39
+ ]
@@ -1,186 +0,0 @@
1
- // GENERATED by scripts/bake-global-peace-index.mjs — do not hand-edit.
2
- // Source: Institute for Economics & Peace, Global Peace Index, 2026
3
- // edition (their own annual report, parsed from its published rankings
4
- // table). Licensed for non-commercial use — see
5
- // mcps/global-peace-index/README.md.
6
- // Captured: 2026-10-18T01:05:31.362Z
7
- // Regenerate: node scripts/bake-global-peace-index.mjs
8
-
9
- export const GPI_EDITION_YEAR = 2026;
10
- export const GPI_CAPTURED_AT = "2026-10-18T01:05:31.362Z";
11
-
12
- export interface GpiCountryRow {
13
- country: string;
14
- /** Lower rank = more peaceful (1 = most peaceful). */
15
- rank: number;
16
- /** GPI score, lower = more peaceful (observed range ~1.1-3.4). */
17
- score: number;
18
- /** Places moved in the ranking vs the prior edition; positive = improved (moved toward 1), negative = worsened, 0 = unchanged. */
19
- rank_change: number;
20
- }
21
-
22
- export const GPI_COUNTRIES: GpiCountryRow[] = [
23
- { country: "Iceland", rank: 1, score: 1.161, rank_change: 0 },
24
- { country: "New Zealand", rank: 2, score: 1.343, rank_change: 1 },
25
- { country: "Switzerland", rank: 3, score: 1.363, rank_change: -1 },
26
- { country: "Slovenia", rank: 4, score: 1.369, rank_change: 2 },
27
- { country: "Ireland", rank: 5, score: 1.371, rank_change: -1 },
28
- { country: "Austria", rank: 6, score: 1.421, rank_change: -1 },
29
- { country: "Portugal", rank: 7, score: 1.427, rank_change: 1 },
30
- { country: "Singapore", rank: 8, score: 1.435, rank_change: -1 },
31
- { country: "Finland", rank: 9, score: 1.478, rank_change: 1 },
32
- { country: "Japan", rank: 10, score: 1.489, rank_change: 3 },
33
- { country: "Denmark", rank: 11, score: 1.504, rank_change: -2 },
34
- { country: "Malaysia", rank: 12, score: 1.513, rank_change: -1 },
35
- { country: "Czechia", rank: 13, score: 1.517, rank_change: -1 },
36
- { country: "Canada", rank: 14, score: 1.525, rank_change: 1 },
37
- { country: "Hungary", rank: 15, score: 1.538, rank_change: -1 },
38
- { country: "Bhutan", rank: 16, score: 1.546, rank_change: 2 },
39
- { country: "Netherlands", rank: 17, score: 1.566, rank_change: 0 },
40
- { country: "Mauritius", rank: 18, score: 1.586, rank_change: 11 },
41
- { country: "Latvia", rank: 19, score: 1.589, rank_change: 0 },
42
- { country: "Australia", rank: 20, score: 1.602, rank_change: 4 },
43
- { country: "Belgium", rank: 21, score: 1.608, rank_change: -5 },
44
- { country: "Poland", rank: 22, score: 1.615, rank_change: 23 },
45
- { country: "Croatia", rank: 23, score: 1.619, rank_change: 2 },
46
- { country: "Lithuania", rank: 24, score: 1.62, rank_change: 3 },
47
- { country: "Estonia", rank: 25, score: 1.623, rank_change: -5 },
48
- { country: "Bulgaria", rank: 26, score: 1.628, rank_change: -4 },
49
- { country: "Spain", rank: 27, score: 1.654, rank_change: 4 },
50
- { country: "Germany", rank: 28, score: 1.657, rank_change: -5 },
51
- { country: "Slovakia", rank: 29, score: 1.661, rank_change: -3 },
52
- { country: "Montenegro", rank: 30, score: 1.672, rank_change: -2 },
53
- { country: "Qatar", rank: 31, score: 1.676, rank_change: -10 },
54
- { country: "Timor-Leste", rank: 32, score: 1.681, rank_change: -2 },
55
- { country: "Norway", rank: 33, score: 1.688, rank_change: 0 },
56
- { country: "Mongolia", rank: 34, score: 1.692, rank_change: 4 },
57
- { country: "Italy", rank: 35, score: 1.712, rank_change: 0 },
58
- { country: "Albania", rank: 36, score: 1.725, rank_change: 7 },
59
- { country: "Uzbekistan", rank: 37, score: 1.726, rank_change: 10 },
60
- { country: "Equatorial Guinea", rank: 38, score: 1.729, rank_change: 20 },
61
- { country: "United Kingdom", rank: 39, score: 1.73, rank_change: -7 },
62
- { country: "Sweden", rank: 40, score: 1.732, rank_change: -1 },
63
- { country: "Vietnam", rank: 41, score: 1.738, rank_change: -1 },
64
- { country: "Taiwan", rank: 42, score: 1.751, rank_change: -5 },
65
- { country: "Uruguay", rank: 43, score: 1.754, rank_change: -1 },
66
- { country: "Kazakhstan", rank: 44, score: 1.771, rank_change: 5 },
67
- { country: "Romania", rank: 45, score: 1.788, rank_change: -1 },
68
- { country: "North Macedonia", rank: 46, score: 1.792, rank_change: 3 },
69
- { country: "Tajikistan", rank: 47, score: 1.799, rank_change: -6 },
70
- { country: "Bosnia and Herzegovina", rank: 48, score: 1.81, rank_change: 9 },
71
- { country: "Kuwait", rank: 49, score: 1.813, rank_change: -13 },
72
- { country: "Botswana", rank: 50, score: 1.823, rank_change: -4 },
73
- { country: "Armenia", rank: 51, score: 1.825, rank_change: 21 },
74
- { country: "Chile", rank: 52, score: 1.826, rank_change: 8 },
75
- { country: "Greece", rank: 53, score: 1.828, rank_change: 2 },
76
- { country: "Kosovo", rank: 54, score: 1.83, rank_change: 0 },
77
- { country: "Moldova", rank: 55, score: 1.836, rank_change: 1 },
78
- { country: "The Gambia", rank: 56, score: 1.837, rank_change: 5 },
79
- { country: "South Korea", rank: 57, score: 1.839, rank_change: -6 },
80
- { country: "Laos", rank: 58, score: 1.846, rank_change: 0 },
81
- { country: "Madagascar", rank: 59, score: 1.849, rank_change: 4 },
82
- { country: "Oman", rank: 60, score: 1.85, rank_change: -26 },
83
- { country: "Kyrgyz Republic", rank: 61, score: 1.853, rank_change: 8 },
84
- { country: "Costa Rica", rank: 62, score: 1.86, rank_change: -14 },
85
- { country: "Namibia", rank: 63, score: 1.872, rank_change: -1 },
86
- { country: "Paraguay", rank: 64, score: 1.882, rank_change: 5 },
87
- { country: "Morocco", rank: 65, score: 1.887, rank_change: 3 },
88
- { country: "Turkmenistan", rank: 66, score: 1.903, rank_change: -2 },
89
- { country: "Sri Lanka", rank: 67, score: 1.91, rank_change: 14 },
90
- { country: "Jordan", rank: 68, score: 1.913, rank_change: 9 },
91
- { country: "Indonesia", rank: 69, score: 1.918, rank_change: -3 },
92
- { country: "Jamaica", rank: 70, score: 1.919, rank_change: -1 },
93
- { country: "Serbia", rank: 70, score: 1.919, rank_change: 5 },
94
- { country: "Argentina", rank: 72, score: 1.922, rank_change: -20 },
95
- { country: "United Arab Emirates", rank: 73, score: 1.927, rank_change: 0 },
96
- { country: "Sierra Leone", rank: 74, score: 1.937, rank_change: 9 },
97
- { country: "Senegal", rank: 75, score: 1.939, rank_change: 12 },
98
- { country: "Ghana", rank: 76, score: 1.943, rank_change: -2 },
99
- { country: "Tunisia", rank: 77, score: 1.947, rank_change: 19 },
100
- { country: "Angola", rank: 78, score: 1.955, rank_change: 11 },
101
- { country: "Trinidad and Tobago", rank: 79, score: 1.959, rank_change: -12 },
102
- { country: "Cyprus", rank: 80, score: 1.967, rank_change: -9 },
103
- { country: "Panama", rank: 81, score: 1.976, rank_change: -6 },
104
- { country: "Zambia", rank: 82, score: 1.992, rank_change: -2 },
105
- { country: "Malawi", rank: 83, score: 1.994, rank_change: -18 },
106
- { country: "Papua New Guinea", rank: 84, score: 2.002, rank_change: 17 },
107
- { country: "Guinea-Bissau", rank: 85, score: 2.012, rank_change: 7 },
108
- { country: "Lesotho", rank: 86, score: 2.016, rank_change: 27 },
109
- { country: "Liberia", rank: 87, score: 2.024, rank_change: 17 },
110
- { country: "Guatemala", rank: 88, score: 2.025, rank_change: -6 },
111
- { country: "Dominican Republic", rank: 89, score: 2.038, rank_change: -10 },
112
- { country: "Zimbabwe", rank: 90, score: 2.051, rank_change: 10 },
113
- { country: "Algeria", rank: 91, score: 2.053, rank_change: -5 },
114
- { country: "Bolivia", rank: 92, score: 2.054, rank_change: -2 },
115
- { country: "Côte d'Ivoire", rank: 93, score: 2.061, rank_change: -9 },
116
- { country: "Georgia", rank: 94, score: 2.066, rank_change: 1 },
117
- { country: "Saudi Arabia", rank: 95, score: 2.067, rank_change: -2 },
118
- { country: "Cambodia", rank: 96, score: 2.075, rank_change: -8 },
119
- { country: "Honduras", rank: 97, score: 2.075, rank_change: 13 },
120
- { country: "Tanzania", rank: 98, score: 2.08, rank_change: -20 },
121
- { country: "France", rank: 99, score: 2.083, rank_change: 3 },
122
- { country: "Gabon", rank: 100, score: 2.086, rank_change: 17 },
123
- { country: "Thailand", rank: 101, score: 2.089, rank_change: -7 },
124
- { country: "Philippines", rank: 102, score: 2.092, rank_change: -3 },
125
- { country: "Guyana", rank: 103, score: 2.093, rank_change: -12 },
126
- { country: "Eswatini", rank: 104, score: 2.095, rank_change: 6 },
127
- { country: "Djibouti", rank: 105, score: 2.098, rank_change: 6 },
128
- { country: "Nicaragua", rank: 106, score: 2.107, rank_change: -9 },
129
- { country: "Peru", rank: 107, score: 2.12, rank_change: -1 },
130
- { country: "Bahrain", rank: 108, score: 2.131, rank_change: 0 },
131
- { country: "Cuba", rank: 109, score: 2.139, rank_change: -11 },
132
- { country: "Azerbaijan", rank: 110, score: 2.142, rank_change: -8 },
133
- { country: "Nepal", rank: 111, score: 2.143, rank_change: -26 },
134
- { country: "Mauritania", rank: 112, score: 2.184, rank_change: 2 },
135
- { country: "Egypt", rank: 113, score: 2.186, rank_change: 2 },
136
- { country: "Rwanda", rank: 114, score: 2.2, rank_change: -2 },
137
- { country: "Belarus", rank: 115, score: 2.216, rank_change: 1 },
138
- { country: "Guinea", rank: 116, score: 2.22, rank_change: 2 },
139
- { country: "Bangladesh", rank: 117, score: 2.226, rank_change: 3 },
140
- { country: "China", rank: 118, score: 2.231, rank_change: -11 },
141
- { country: "Togo", rank: 119, score: 2.251, rank_change: 7 },
142
- { country: "Republic of the Congo", rank: 120, score: 2.256, rank_change: -15 },
143
- { country: "El Salvador", rank: 121, score: 2.264, rank_change: 1 },
144
- { country: "Benin", rank: 122, score: 2.293, rank_change: -1 },
145
- { country: "South Africa", rank: 123, score: 2.308, rank_change: -4 },
146
- { country: "Brazil", rank: 124, score: 2.333, rank_change: 1 },
147
- { country: "Libya", rank: 125, score: 2.361, rank_change: 3 },
148
- { country: "Mozambique", rank: 126, score: 2.383, rank_change: 1 },
149
- { country: "India", rank: 127, score: 2.409, rank_change: -3 },
150
- { country: "Eritrea", rank: 128, score: 2.412, rank_change: 3 },
151
- { country: "Burundi", rank: 129, score: 2.417, rank_change: 6 },
152
- { country: "Uganda", rank: 130, score: 2.42, rank_change: -7 },
153
- { country: "Lebanon", rank: 131, score: 2.435, rank_change: 3 },
154
- { country: "Kenya", rank: 132, score: 2.447, rank_change: 1 },
155
- { country: "Venezuela", rank: 133, score: 2.516, rank_change: -4 },
156
- { country: "United States of America", rank: 134, score: 2.535, rank_change: -4 },
157
- { country: "Ecuador", rank: 135, score: 2.539, rank_change: -3 },
158
- { country: "Türkiye", rank: 136, score: 2.605, rank_change: 8 },
159
- { country: "Cameroon", rank: 137, score: 2.634, rank_change: 5 },
160
- { country: "Ethiopia", rank: 138, score: 2.648, rank_change: 1 },
161
- { country: "Mexico", rank: 139, score: 2.65, rank_change: 4 },
162
- { country: "Iraq", rank: 140, score: 2.662, rank_change: 0 },
163
- { country: "Colombia", rank: 141, score: 2.735, rank_change: -4 },
164
- { country: "Haiti", rank: 142, score: 2.755, rank_change: -1 },
165
- { country: "Nigeria", rank: 142, score: 2.755, rank_change: 6 },
166
- { country: "Iran", rank: 144, score: 2.759, rank_change: -6 },
167
- { country: "Chad", rank: 145, score: 2.769, rank_change: -9 },
168
- { country: "Niger", rank: 146, score: 2.832, rank_change: -1 },
169
- { country: "North Korea", rank: 147, score: 2.845, rank_change: 0 },
170
- { country: "Palestine", rank: 148, score: 2.877, rank_change: 2 },
171
- { country: "Burkina Faso", rank: 149, score: 2.882, rank_change: 3 },
172
- { country: "Central African Republic", rank: 150, score: 2.906, rank_change: 1 },
173
- { country: "Myanmar", rank: 151, score: 2.911, rank_change: 2 },
174
- { country: "Pakistan", rank: 152, score: 2.919, rank_change: -6 },
175
- { country: "Somalia", rank: 153, score: 2.973, rank_change: -4 },
176
- { country: "Mali", rank: 154, score: 2.996, rank_change: 0 },
177
- { country: "Syria", rank: 155, score: 3.067, rank_change: 0 },
178
- { country: "Yemen", rank: 156, score: 3.081, rank_change: 2 },
179
- { country: "Afghanistan", rank: 157, score: 3.106, rank_change: 0 },
180
- { country: "South Sudan", rank: 158, score: 3.116, rank_change: -2 },
181
- { country: "Israel", rank: 159, score: 3.124, rank_change: 1 },
182
- { country: "Ukraine", rank: 160, score: 3.184, rank_change: 2 },
183
- { country: "Democratic Republic of the Congo", rank: 161, score: 3.189, rank_change: 0 },
184
- { country: "Sudan", rank: 162, score: 3.195, rank_change: -3 },
185
- { country: "Russia", rank: 163, score: 3.367, rank_change: 0 },
186
- ];
package/src/index.ts DELETED
@@ -1,190 +0,0 @@
1
- interface McpToolDefinition {
2
- name: string;
3
- description: string;
4
- /** Human-facing one-liner (fleet #1967). Optional; consumers fall back to
5
- * description. Kept in step with shared/src/types.ts — scripts/lib/
6
- * check-inlined-types.mjs reports drift at publish time. */
7
- summary?: string;
8
- inputSchema: {
9
- type: 'object';
10
- properties: Record<string, unknown>;
11
- required?: string[];
12
- anyOf?: Array<{ required: string[] }>;
13
- oneOf?: Array<{ required: string[] }>;
14
- allOf?: Array<{ required: string[] }>;
15
- };
16
- outputSchema?: Record<string, unknown>;
17
- }
18
-
19
- interface McpToolExport {
20
- tools: McpToolDefinition[];
21
- callTool: (name: string, args: Record<string, unknown>) => Promise<unknown>;
22
- meter?: { credits: number };
23
- cost?: Record<string, unknown>;
24
- provider?: string;
25
- }
26
-
27
- /**
28
- * Global Peace Index — annual country peacefulness score and rank, for
29
- * country-risk context alongside event/news data (fleet #3276).
30
- *
31
- * Publisher + dataset: Institute for Economics & Peace, Global Peace Index.
32
- * Published annually as a report (no live query API), so this pack reads
33
- * from a baked copy rather than proxying per request — see
34
- * workers/gateway/src/pack-baked-indexes.json and scripts/bake-global-peace-index.mjs
35
- * for the refresh path. NEVER value-import the data module here (fleet
36
- * #2754 — it goes into every gateway isolate's bundle whether or not that
37
- * isolate ever serves this pack); only type-only imports are allowed.
38
- *
39
- * LICENCE: the Institute for Economics & Peace's official GPI data download
40
- * carries a stated non-commercial licence, and its Terms & Conditions
41
- * require written permission to republish. Bruce ruled 2026-10-17
42
- * (build-anyway-zero-rate) to ship it anyway with the whole pack zero-rated
43
- * — see pack-manifest.json's `zeroRated`/`zeroRatedReason` for this pack.
44
- * Every response carries the publisher's attribution in its `source` field.
45
- */
46
- import type { GpiCountryRow } from './gpi-index-data.js';
47
-
48
- const SOURCE = 'Institute for Economics & Peace, Global Peace Index';
49
-
50
- // fleet #2754: the baked index lives in KV, injected as args._bakedIndex on
51
- // the first call into this pack, never imported at module scope.
52
- let GPI_COUNTRIES: GpiCountryRow[] = [];
53
- let GPI_EDITION_YEAR = 0;
54
- let GPI_CAPTURED_AT = '';
55
-
56
- function ensureIndex(args: Record<string, unknown>): void {
57
- if (GPI_COUNTRIES.length) return;
58
- const idx = args._bakedIndex as Record<string, unknown> | null | undefined;
59
- const countries = idx?.GPI_COUNTRIES;
60
- const year = idx?.GPI_EDITION_YEAR;
61
- const capturedAt = idx?.GPI_CAPTURED_AT;
62
- if (!Array.isArray(countries) || countries.length === 0 || typeof year !== 'number' || typeof capturedAt !== 'string') {
63
- throw new Error(
64
- 'global-peace-index: the baked index is unavailable (not injected or malformed). ' +
65
- 'The gateway loads it from KV on the first call into this pack; this is a server-side fault, not a bad country name — retry shortly.',
66
- );
67
- }
68
- GPI_COUNTRIES = countries as GpiCountryRow[];
69
- GPI_EDITION_YEAR = year;
70
- GPI_CAPTURED_AT = capturedAt;
71
- }
72
-
73
- // A handful of names callers reach for that do not match the publisher's own
74
- // spelling (verified against the baked rows: "United States of America",
75
- // "Democratic Republic of the Congo", "Republic of the Congo", ...).
76
- const ALIASES: Record<string, string> = {
77
- usa: 'united states of america',
78
- us: 'united states of america',
79
- 'united states': 'united states of america',
80
- america: 'united states of america',
81
- uk: 'united kingdom',
82
- britain: 'united kingdom',
83
- drc: 'democratic republic of the congo',
84
- 'dr congo': 'democratic republic of the congo',
85
- 'democratic republic of congo': 'democratic republic of the congo',
86
- 'congo-kinshasa': 'democratic republic of the congo',
87
- 'congo-brazzaville': 'republic of the congo',
88
- 'ivory coast': "cote d'ivoire",
89
- 'north korea': 'north korea',
90
- 'south korea': 'south korea',
91
- };
92
-
93
- function normalize(s: string): string {
94
- return s.trim().toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '');
95
- }
96
-
97
- function findCountry(query: string): { row: GpiCountryRow | null; candidates: string[] } {
98
- const q = normalize(query);
99
- const aliased = ALIASES[q] ?? q;
100
- const byExact = GPI_COUNTRIES.find((r) => normalize(r.country) === aliased);
101
- if (byExact) return { row: byExact, candidates: [] };
102
- const contains = GPI_COUNTRIES.filter((r) => normalize(r.country).includes(aliased) || aliased.includes(normalize(r.country)));
103
- if (contains.length === 1) return { row: contains[0]!, candidates: [] };
104
- return { row: null, candidates: contains.map((r) => r.country) };
105
- }
106
-
107
- const tools: McpToolExport['tools'] = [
108
- {
109
- name: 'gpi_country_score',
110
- description:
111
- 'Global Peace Index score and rank for ONE country — a country peacefulness measure (societal safety, ongoing conflict, and militarisation indicators rolled into one score; LOWER = more peaceful). Published annually by the Institute for Economics & Peace. PREFER for "how peaceful is <country>", "<country> global peace index", "peace ranking for <country>", or as background context on a country before/alongside news-event data (complements gdelt). Pass a country name (e.g. "Iceland", "Russia", "United States" — common aliases like "USA"/"DRC" are accepted).',
112
- inputSchema: {
113
- type: 'object',
114
- properties: {
115
- country: { type: 'string', description: 'Country name (e.g. "Ukraine", "Japan", "USA").' },
116
- },
117
- required: ['country'],
118
- },
119
- },
120
- {
121
- name: 'gpi_ranking',
122
- description:
123
- 'Rank countries by Global Peace Index score — the N most peaceful or N least peaceful countries in one call, with rank and score. PREFER for "most peaceful countries", "least peaceful/most dangerous countries", "top 10 most peaceful nations", "which countries have the worst peace ranking". direction defaults to "most_peaceful".',
124
- inputSchema: {
125
- type: 'object',
126
- properties: {
127
- limit: { type: 'number', description: 'How many countries to return (default 10, max 50).' },
128
- direction: { type: 'string', enum: ['most_peaceful', 'least_peaceful'], description: 'Which end of the ranking to return. Default "most_peaceful".' },
129
- },
130
- },
131
- },
132
- ];
133
-
134
- async function callTool(name: string, args: Record<string, unknown>): Promise<unknown> {
135
- ensureIndex(args);
136
- switch (name) {
137
- case 'gpi_country_score':
138
- return gpiCountryScore(String(args.country ?? args.country_name ?? '').trim());
139
- case 'gpi_ranking':
140
- return gpiRanking(
141
- typeof args.limit === 'number' ? args.limit : Number(args.limit) || 10,
142
- args.direction === 'least_peaceful' ? 'least_peaceful' : 'most_peaceful',
143
- );
144
- default:
145
- throw new Error(`Unknown tool: ${name}`);
146
- }
147
- }
148
-
149
- function gpiCountryScore(country: string) {
150
- if (!country) {
151
- throw new Error('Pass a country name, e.g. gpi_country_score({country: "Iceland"}).');
152
- }
153
- const { row, candidates } = findCountry(country);
154
- if (!row) {
155
- throw new Error(
156
- candidates.length > 1
157
- ? `user_error: "${country}" matches more than one country in the Global Peace Index: ${candidates.join(', ')}. Pass one of those exact names.`
158
- : `user_error: No Global Peace Index entry found for "${country}". The Index covers ${GPI_COUNTRIES.length} countries/territories; check the spelling.`,
159
- );
160
- }
161
- return {
162
- country: row.country,
163
- year: GPI_EDITION_YEAR,
164
- rank: row.rank,
165
- total_countries: GPI_COUNTRIES.length,
166
- score: row.score,
167
- scale: 'lower = more peaceful (observed range ~1.1-3.4)',
168
- rank_change_vs_prior_edition: row.rank_change,
169
- source: SOURCE,
170
- data_as_of: GPI_CAPTURED_AT,
171
- };
172
- }
173
-
174
- function gpiRanking(limitRaw: number, direction: 'most_peaceful' | 'least_peaceful') {
175
- const limit = Math.max(1, Math.min(50, Number.isFinite(limitRaw) && limitRaw > 0 ? Math.floor(limitRaw) : 10));
176
- const sorted = [...GPI_COUNTRIES].sort((a, b) => (direction === 'most_peaceful' ? a.rank - b.rank : b.rank - a.rank));
177
- const slice = sorted.slice(0, limit);
178
- return {
179
- direction,
180
- returned: slice.length,
181
- total_countries: GPI_COUNTRIES.length,
182
- year: GPI_EDITION_YEAR,
183
- scale: 'lower = more peaceful (observed range ~1.1-3.4)',
184
- source: SOURCE,
185
- data_as_of: GPI_CAPTURED_AT,
186
- ranking: slice.map((r) => ({ rank: r.rank, country: r.country, score: r.score, rank_change_vs_prior_edition: r.rank_change })),
187
- };
188
- }
189
-
190
- export default { tools, callTool, meter: { credits: 1 } } satisfies McpToolExport;
package/src/server.ts DELETED
@@ -1,49 +0,0 @@
1
- /**
2
- * Stdio MCP server entry point for @pipeworx/mcp-global-peace-index.
3
- * Generated by scripts/publish-pack.sh — do not hand-edit in the pack repo;
4
- * edit scripts/publish-pack.sh (the server.ts heredoc) and republish instead.
5
- */
6
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
7
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
8
- import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
9
- import pack from './index.js';
10
- import * as bakedIndexModule from './gpi-index-data.js';
11
- const bakedIndex = Object.fromEntries(Object.entries(bakedIndexModule));
12
-
13
- const server = new Server(
14
- { name: '@pipeworx/mcp-global-peace-index', version: '0.1.0' },
15
- { capabilities: { tools: {} } },
16
- );
17
-
18
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
19
- tools: pack.tools.map((t) => ({
20
- name: t.name,
21
- description: t.description,
22
- inputSchema: t.inputSchema,
23
- })),
24
- }));
25
-
26
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
27
- const { name, arguments: args } = request.params;
28
- try {
29
- const callArgs = { ...((args ?? {}) as Record<string, unknown>) };
30
- callArgs._bakedIndex = bakedIndex;
31
- const result = await pack.callTool(name, callArgs);
32
- return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
33
- } catch (err) {
34
- return {
35
- content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }],
36
- isError: true,
37
- };
38
- }
39
- });
40
-
41
- async function main() {
42
- const transport = new StdioServerTransport();
43
- await server.connect(transport);
44
- }
45
-
46
- main().catch((err) => {
47
- console.error('Fatal error running server:', err);
48
- process.exit(1);
49
- });
package/tsconfig.json DELETED
@@ -1,18 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2022",
4
- "module": "ESNext",
5
- "moduleResolution": "bundler",
6
- "lib": ["ES2022"],
7
- "types": ["@cloudflare/workers-types"],
8
- "strict": true,
9
- "esModuleInterop": true,
10
- "skipLibCheck": true,
11
- "resolveJsonModule": true,
12
- "outDir": "dist",
13
- "rootDir": "src",
14
- "declaration": true
15
- },
16
- "include": ["src"],
17
- "exclude": ["src/server.ts"]
18
- }