@reneturcios/polyguide 0.0.0-stage → 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 Rene Turcios
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 CHANGED
@@ -1,3 +1,84 @@
1
- # Temporary Holding Version
1
+ # polyguide
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Finding a polygraph examination office and reading its published prices, without submitting anything. polyguide is a local forwarding client for the hosted LieDetectorTest MCP service: it answers `tools/list` on your own machine from the captured tool definitions and forwards every read to the service, returning the answers exactly as they come back.
4
+
5
+ Everything here is a published read, plus one status read keyed by a reference you already hold. You can search for offices across the United States, Canada and the United Kingdom, read the all-inclusive price tiers for a location, pull up general information about how the service, booking and payment work, and check the status of an existing booking by its reference. No tool in this package starts a booking or sends anyone's details anywhere.
6
+
7
+ ## The tools
8
+
9
+ - **`find_offices`** — Offices near a place. Search by city, state or region, or country, and get each matching office with its address, all-inclusive prices and a booking link. `query` is required; `limit` (1–50, default 15) is optional.
10
+ - **`get_pricing`** — Price tiers for a location: single person, couple or two-person total, and group per-examinee, plus how payment works. Nothing is paid online; the client pays the examiner directly once the examiner accepts the case. `query` is required.
11
+ - **`get_service_info`** — General information: what is offered, how booking works, how payment works, the service area, and what happens after booking. Takes no arguments.
12
+ - **`get_booking_status`** — The status and location for an existing booking or appointment request, looked up by its `booking_reference` (for example `LDT-2026072062783`). A status of "request" means the request has been sent to the examiner, who will contact the person directly.
13
+
14
+ One upstream tool is deliberately not included: the booking-start tool, which would send an appointment request for a named person, with that person's email address, directly to the examiner. It is not registered, not served over MCP, and has no CLI subcommand.
15
+
16
+ ## Install and run
17
+
18
+ As an MCP server via npm:
19
+
20
+ ```bash
21
+ npx -y @reneturcios/polyguide mcp
22
+ ```
23
+
24
+ MCP client configuration:
25
+
26
+ ```json
27
+ {
28
+ "mcpServers": {
29
+ "polyguide": {
30
+ "command": "npx",
31
+ "args": ["-y", "@reneturcios/polyguide", "mcp"]
32
+ }
33
+ }
34
+ }
35
+ ```
36
+
37
+ As a container:
38
+
39
+ ```bash
40
+ docker run -i ghcr.io/cloudcorprecords/polyguide
41
+ docker run --rm ghcr.io/cloudcorprecords/polyguide get_service_info '{}'
42
+ ```
43
+
44
+ ## CLI
45
+
46
+ One binary serves both the command line and the MCP server. Each tool is a subcommand taking a single JSON string with that tool's arguments:
47
+
48
+ ```bash
49
+ polyguide find_offices '{"query":"Miami"}'
50
+ polyguide find_offices '{"query":"Florida","limit":5}'
51
+ polyguide get_pricing '{"query":"Texas"}'
52
+ polyguide get_service_info '{}'
53
+ polyguide get_booking_status '{"booking_reference":"LDT-2026072062783"}'
54
+ polyguide --version
55
+ ```
56
+
57
+ Exit codes: `0` when the forwarded call succeeds, `1` when the upstream result is an error, and `2` for usage problems such as an unknown subcommand or a malformed JSON argument.
58
+
59
+ ## Configuration
60
+
61
+ - `LIEDETECTORTEST_MCP_URL` — Overrides the upstream endpoint. The default is the pinned hosted endpoint, `https://liedetectortest.com/wp-json/ldt-mcp/v1/mcp`. (The override variable is a reconstruction added by this rebuild.)
62
+
63
+ The LieDetectorTest registry record declares no headers on its remote, so polyguide sends no authentication header of any kind — the reads are keyless.
64
+
65
+ Upstream failures — a JSON-RPC error from the service, a non-2xx response, an unreadable body, or a request that fails outright — are reported to the caller as an error result whose text starts with `polyguide error:`.
66
+
67
+ ## How forwarding works
68
+
69
+ The first forwarded call opens a session: an `initialize` request (protocol version `2025-03-26`), followed by a `notifications/initialized` notification, then the `tools/call` itself. If the service answers the initialize request with an `Mcp-Session-Id` header, that value is carried on every later request, and the open session is reused for the rest of the process. Replies are accepted either as plain JSON or as server-sent events. Successful results pass through verbatim, including any `isError` flag and any extra fields the service includes.
70
+
71
+ ## Development
72
+
73
+ ```bash
74
+ npm install
75
+ npm run build # tsc -> dist/ (dist/cli.js is the bin)
76
+ npm test # tsx --test test/*.test.ts — stubbed upstream, no network
77
+ npm run dev # run the CLI from source
78
+ ```
79
+
80
+ The test suite checks the served tool list against the captured subset, asserts the omitted booking-start tool is absent at registry, MCP and CLI level, exercises the session handshake and its reuse, asserts that no `Authorization` header is sent under any environment, and verifies that arguments go upstream untouched and results come back untouched.
81
+
82
+ ## License
83
+
84
+ MIT — see `LICENSE`. Copyright (c) 2026 Rene Turcios.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * polyguide CLI.
4
+ *
5
+ * polyguide <tool> '<json-args>'
6
+ * polyguide mcp
7
+ * polyguide --version
8
+ *
9
+ * <tool> is one of the 4 captured subset forwarded tools.
10
+ * Each tool subcommand takes a single JSON argument string
11
+ * holding that tool's arguments, forwards the call the
12
+ * same way the MCP path does, and prints the forwarded
13
+ * result content. Exit codes: 0 success, 1 on an
14
+ * isError result, 2 usage error.
15
+ */
16
+ import { callTool, TOOL_NAMES, VERSION } from "./forward.js";
17
+ function usage() {
18
+ console.error(`Usage:
19
+ polyguide <tool> '<json-args>' one of: ${TOOL_NAMES.join(", ")}
20
+ polyguide mcp
21
+ polyguide --version`);
22
+ process.exit(2);
23
+ }
24
+ function firstText(result) {
25
+ const content = result.content;
26
+ if (Array.isArray(content)) {
27
+ for (const item of content) {
28
+ if (item !== null &&
29
+ typeof item === "object" &&
30
+ item.type === "text" &&
31
+ typeof item.text === "string") {
32
+ return item.text;
33
+ }
34
+ }
35
+ }
36
+ return typeof content === "string" ? content : JSON.stringify(content);
37
+ }
38
+ async function main() {
39
+ const [cmd, ...rest] = process.argv.slice(2);
40
+ if (cmd === "--version" || cmd === "-v") {
41
+ console.log(VERSION);
42
+ return;
43
+ }
44
+ if (cmd === "mcp") {
45
+ if (rest.length !== 0)
46
+ usage();
47
+ const { startMcpServer } = await import("./mcp.js");
48
+ await startMcpServer();
49
+ return;
50
+ }
51
+ if (!TOOL_NAMES.includes(cmd ?? ""))
52
+ usage();
53
+ if (rest.length > 1)
54
+ usage();
55
+ let args = {};
56
+ if (rest.length === 1) {
57
+ try {
58
+ const parsed = JSON.parse(rest[0]);
59
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
60
+ usage();
61
+ }
62
+ args = parsed;
63
+ }
64
+ catch {
65
+ console.error("error: argument must be a JSON object string");
66
+ process.exit(2);
67
+ }
68
+ }
69
+ const result = await callTool(cmd, args);
70
+ if (result.isError) {
71
+ console.error(`error: ${firstText(result)}`);
72
+ process.exit(1);
73
+ }
74
+ console.log(typeof result.content === "string"
75
+ ? result.content
76
+ : JSON.stringify(result.content, null, 2));
77
+ }
78
+ void main();
79
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":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,IAAI,EAAE,CAAC,CAAC,CAC5C,CAAC;AACJ,CAAC;AAED,KAAK,IAAI,EAAE,CAAC"}
@@ -0,0 +1,83 @@
1
+ /**
2
+ * polyguide core: a forwarding client for the hosted
3
+ * LieDetectorTest MCP server.
4
+ *
5
+ * No directory data lives on this machine. tools/list is
6
+ * answered from the literal definitions below, which
7
+ * reproduce a live capture of the upstream server word
8
+ * for word (name, description and inputSchema exactly
9
+ * as captured). A tools/call travels upstream over a
10
+ * streamable-HTTP JSON-RPC session: an initialize POST,
11
+ * a notifications/initialized POST, then the tools/call
12
+ * POST, carrying the Mcp-Session-Id response header on
13
+ * later requests when the upstream issues one. The
14
+ * session opens lazily on the first forwarded call and
15
+ * is reused for the client's lifetime.
16
+ *
17
+ * The endpoint is pinned to
18
+ * https://liedetectortest.com/wp-json/ldt-mcp/v1/mcp
19
+ * and may be replaced with the LIEDETECTORTEST_MCP_URL
20
+ * environment variable (that override is a labelled
21
+ * reconstruction). The registry record declares NO
22
+ * headers on the remote: no auth header is ever sent,
23
+ * under any environment.
24
+ *
25
+ * One of the upstream's five captured tools is
26
+ * deliberately omitted from this rebuild (see the
27
+ * build report): it sends an appointment request for
28
+ * a named person, with that person's email, directly
29
+ * to the examiner. The omitted tool is not registered,
30
+ * not served, and not reachable from the CLI.
31
+ *
32
+ * A successful upstream result is returned exactly as
33
+ * received, isError flag and extra fields included.
34
+ * Failures — an upstream JSON-RPC error, a non-2xx
35
+ * status, a body that cannot be parsed, or a fetch
36
+ * that throws or times out — become an isError result
37
+ * whose text begins with `polyguide error:` (that
38
+ * rendering is a labelled reconstruction). Replies may
39
+ * be plain JSON or SSE (`data:` lines); the JSON-RPC
40
+ * message whose id matches the request wins.
41
+ */
42
+ import type { ForwardDeps, ToolArgs, ToolDef, ToolResult } from "./types.js";
43
+ export declare const VERSION = "0.1.0";
44
+ export declare const DEFAULT_ENDPOINT_URL = "https://liedetectortest.com/wp-json/ldt-mcp/v1/mcp";
45
+ export declare const DEFAULT_TIMEOUT_MS = 30000;
46
+ export declare const PROTOCOL_VERSION = "2025-03-26";
47
+ export declare const TOOL_DEFS: ToolDef[];
48
+ export declare const TOOL_NAMES: string[];
49
+ /** Whether `name` belongs to the captured subset surface. */
50
+ export declare function isKnownTool(name: string): boolean;
51
+ /**
52
+ * Read a JSON-RPC response body, tolerating SSE framing.
53
+ * Returns the message whose id matches `expectedId` when
54
+ * present, otherwise the last parseable message, otherwise
55
+ * null when nothing in the body parses.
56
+ */
57
+ export declare function parseRpcBody(text: string, expectedId?: number): Record<string, unknown> | null;
58
+ /**
59
+ * A forwarding client holding a single upstream session,
60
+ * opened lazily on first use and reused from then on
61
+ * (for the process lifetime in the MCP server, or for a
62
+ * single invocation in the CLI).
63
+ */
64
+ export declare class PolyguideClient {
65
+ private readonly deps;
66
+ private sessionId;
67
+ private ready;
68
+ private sessionPromise;
69
+ private idCounter;
70
+ constructor(deps?: ForwardDeps);
71
+ private fetchFn;
72
+ private endpointUrl;
73
+ private timeoutMs;
74
+ private nextId;
75
+ private post;
76
+ private ensureSession;
77
+ /** Forward one tool call; upstream failures come back as isError results. */
78
+ callTool(name: string, args: ToolArgs): Promise<ToolResult>;
79
+ }
80
+ /** Build a forwarding client; tests inject a fake fetch and env through deps. */
81
+ export declare function createClient(deps?: ForwardDeps): PolyguideClient;
82
+ /** One-shot helper: a fresh client for a single call (the CLI path). */
83
+ export declare function callTool(name: string, args: ToolArgs, deps?: ForwardDeps): Promise<ToolResult>;
@@ -0,0 +1,298 @@
1
+ export const VERSION = "0.1.0";
2
+ export const DEFAULT_ENDPOINT_URL = "https://liedetectortest.com/wp-json/ldt-mcp/v1/mcp";
3
+ export const DEFAULT_TIMEOUT_MS = 30000;
4
+ export const PROTOCOL_VERSION = "2025-03-26";
5
+ /* ------------------------------------------------------------------ */
6
+ /* Tool definitions (tools/list literals, verbatim from the live */
7
+ /* capture in harness/fixtures/liedetectortest-tools-original.json; */
8
+ /* generated programmatically by parsing and re-serialising the */
9
+ /* fixture JSON, never retyped) */
10
+ /* ------------------------------------------------------------------ */
11
+ export const TOOL_DEFS = [
12
+ {
13
+ "name": "find_offices",
14
+ "description": "Find lie detector (polygraph) test offices near a place. Search by city, state/region, or country (United States, Canada, or United Kingdom). Returns each matching office with its address, all-inclusive prices, and a booking link.",
15
+ "inputSchema": {
16
+ "type": "object",
17
+ "properties": {
18
+ "query": {
19
+ "type": "string",
20
+ "description": "A city, state/region, or country, e.g. \"Miami\", \"Florida\", \"London\", \"Ontario\"."
21
+ },
22
+ "limit": {
23
+ "type": "integer",
24
+ "description": "Maximum offices to return (1-50, default 15)."
25
+ }
26
+ },
27
+ "required": [
28
+ "query"
29
+ ]
30
+ }
31
+ },
32
+ {
33
+ "name": "get_pricing",
34
+ "description": "Get polygraph examination pricing for a location. Returns the all-inclusive price tiers (single person, couple/two-person total, and group per-examinee) and how payment works: there is no booking fee and nothing is paid online or to LieDetectorTest.com — the client pays the examiner directly once the examiner accepts the case.",
35
+ "inputSchema": {
36
+ "type": "object",
37
+ "properties": {
38
+ "query": {
39
+ "type": "string",
40
+ "description": "A city, state/region, or country, e.g. \"Miami\", \"Texas\", \"United Kingdom\"."
41
+ }
42
+ },
43
+ "required": [
44
+ "query"
45
+ ]
46
+ }
47
+ },
48
+ {
49
+ "name": "get_service_info",
50
+ "description": "Get general information about the lie detector test service: what is offered, how booking works, how payment works, the service area, and what happens after booking. Takes no arguments.",
51
+ "inputSchema": {
52
+ "type": "object",
53
+ "properties": {}
54
+ }
55
+ },
56
+ {
57
+ "name": "get_booking_status",
58
+ "description": "Check the status of an existing booking or appointment request by its reference (e.g. LDT-2026072062783). Returns the status and location. Status \"request\" means the request has been sent to the examiner, who will contact the person directly.",
59
+ "inputSchema": {
60
+ "type": "object",
61
+ "properties": {
62
+ "booking_reference": {
63
+ "type": "string",
64
+ "description": "The booking reference, e.g. \"LDT-2026072062783\"."
65
+ }
66
+ },
67
+ "required": [
68
+ "booking_reference"
69
+ ]
70
+ }
71
+ }
72
+ ];
73
+ export const TOOL_NAMES = TOOL_DEFS.map((t) => t.name);
74
+ /** Whether `name` belongs to the captured subset surface. */
75
+ export function isKnownTool(name) {
76
+ return TOOL_NAMES.includes(name);
77
+ }
78
+ /* ------------------------------------------------------------------ */
79
+ /* Forwarding client */
80
+ /* ------------------------------------------------------------------ */
81
+ function errorResult(detail) {
82
+ return {
83
+ content: [{ type: "text", text: `polyguide error: ${detail}` }],
84
+ isError: true,
85
+ };
86
+ }
87
+ function rpcErrorMessage(error) {
88
+ if (error !== null && typeof error === "object") {
89
+ const message = error.message;
90
+ if (typeof message === "string" && message !== "")
91
+ return message;
92
+ return JSON.stringify(error);
93
+ }
94
+ return String(error);
95
+ }
96
+ /**
97
+ * Read a JSON-RPC response body, tolerating SSE framing.
98
+ * Returns the message whose id matches `expectedId` when
99
+ * present, otherwise the last parseable message, otherwise
100
+ * null when nothing in the body parses.
101
+ */
102
+ export function parseRpcBody(text, expectedId) {
103
+ const trimmed = text.trim();
104
+ if (trimmed === "")
105
+ return null;
106
+ const candidates = [];
107
+ const tryPush = (payload) => {
108
+ try {
109
+ const parsed = JSON.parse(payload);
110
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
111
+ candidates.push(parsed);
112
+ }
113
+ }
114
+ catch {
115
+ // Not a JSON payload; skip this candidate.
116
+ }
117
+ };
118
+ if (trimmed.includes("data:")) {
119
+ for (const line of trimmed.split("\n")) {
120
+ const t = line.trim();
121
+ if (!t.startsWith("data:"))
122
+ continue;
123
+ const payload = t.slice("data:".length).trim();
124
+ if (payload !== "" && payload !== "[DONE]")
125
+ tryPush(payload);
126
+ }
127
+ }
128
+ else {
129
+ tryPush(trimmed);
130
+ }
131
+ if (candidates.length === 0)
132
+ return null;
133
+ if (expectedId !== undefined) {
134
+ const match = candidates.find((c) => c.id === expectedId);
135
+ if (match !== undefined)
136
+ return match;
137
+ }
138
+ return candidates[candidates.length - 1];
139
+ }
140
+ async function defaultFetch(url, init) {
141
+ return fetch(url, init);
142
+ }
143
+ /**
144
+ * A forwarding client holding a single upstream session,
145
+ * opened lazily on first use and reused from then on
146
+ * (for the process lifetime in the MCP server, or for a
147
+ * single invocation in the CLI).
148
+ */
149
+ export class PolyguideClient {
150
+ deps;
151
+ sessionId = null;
152
+ ready = false;
153
+ sessionPromise = null;
154
+ idCounter = 0;
155
+ constructor(deps = {}) {
156
+ this.deps = deps;
157
+ }
158
+ fetchFn() {
159
+ return this.deps.fetchFn ?? defaultFetch;
160
+ }
161
+ endpointUrl() {
162
+ if (this.deps.url && this.deps.url.trim() !== "")
163
+ return this.deps.url.trim();
164
+ const raw = (this.deps.env ?? process.env).LIEDETECTORTEST_MCP_URL;
165
+ if (raw && raw.trim() !== "")
166
+ return raw.trim();
167
+ return DEFAULT_ENDPOINT_URL;
168
+ }
169
+ timeoutMs() {
170
+ if (typeof this.deps.timeoutMs === "number" && this.deps.timeoutMs > 0) {
171
+ return this.deps.timeoutMs;
172
+ }
173
+ return DEFAULT_TIMEOUT_MS;
174
+ }
175
+ nextId() {
176
+ this.idCounter += 1;
177
+ return this.idCounter;
178
+ }
179
+ async post(body, withSession) {
180
+ // The registry record declares NO headers on the remote:
181
+ // no Authorization (or any other auth) header is ever sent.
182
+ const headers = {
183
+ "Content-Type": "application/json",
184
+ Accept: "application/json, text/event-stream",
185
+ };
186
+ if (withSession && this.sessionId !== null) {
187
+ headers["Mcp-Session-Id"] = this.sessionId;
188
+ }
189
+ const controller = new AbortController();
190
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs());
191
+ try {
192
+ return await this.fetchFn()(this.endpointUrl(), {
193
+ method: "POST",
194
+ headers,
195
+ body: JSON.stringify(body),
196
+ signal: controller.signal,
197
+ });
198
+ }
199
+ finally {
200
+ clearTimeout(timer);
201
+ }
202
+ }
203
+ async ensureSession() {
204
+ if (this.ready)
205
+ return;
206
+ if (this.sessionPromise === null) {
207
+ this.sessionPromise = (async () => {
208
+ const initId = this.nextId();
209
+ const initRes = await this.post({
210
+ jsonrpc: "2.0",
211
+ id: initId,
212
+ method: "initialize",
213
+ params: {
214
+ protocolVersion: PROTOCOL_VERSION,
215
+ capabilities: {},
216
+ clientInfo: { name: "polyguide", version: VERSION },
217
+ },
218
+ }, false);
219
+ const sessionId = initRes.headers.get("mcp-session-id");
220
+ if (sessionId)
221
+ this.sessionId = sessionId;
222
+ const initText = await initRes.text();
223
+ const initParsed = parseRpcBody(initText, initId);
224
+ if (initParsed !== null && initParsed.error) {
225
+ throw new Error(rpcErrorMessage(initParsed.error));
226
+ }
227
+ if (initRes.status < 200 || initRes.status >= 300) {
228
+ throw new Error(`HTTP ${initRes.status}`);
229
+ }
230
+ if (initParsed === null && initText.trim() !== "") {
231
+ throw new Error("malformed response");
232
+ }
233
+ const initializedRes = await this.post({ jsonrpc: "2.0", method: "notifications/initialized" }, true);
234
+ try {
235
+ await initializedRes.text();
236
+ }
237
+ catch {
238
+ // Nothing needed from the notification response body.
239
+ }
240
+ this.ready = true;
241
+ })();
242
+ }
243
+ try {
244
+ await this.sessionPromise;
245
+ }
246
+ catch (err) {
247
+ this.sessionPromise = null;
248
+ this.sessionId = null;
249
+ throw err;
250
+ }
251
+ }
252
+ /** Forward one tool call; upstream failures come back as isError results. */
253
+ async callTool(name, args) {
254
+ try {
255
+ await this.ensureSession();
256
+ }
257
+ catch (err) {
258
+ return errorResult(err instanceof Error ? err.message : String(err));
259
+ }
260
+ const callId = this.nextId();
261
+ let callRes;
262
+ try {
263
+ callRes = await this.post({
264
+ jsonrpc: "2.0",
265
+ id: callId,
266
+ method: "tools/call",
267
+ params: { name, arguments: args ?? {} },
268
+ }, true);
269
+ }
270
+ catch (err) {
271
+ return errorResult(`request failed: ${err instanceof Error ? err.message : String(err)}`);
272
+ }
273
+ const parsed = parseRpcBody(await callRes.text(), callId);
274
+ if (parsed !== null && parsed.error) {
275
+ return errorResult(rpcErrorMessage(parsed.error));
276
+ }
277
+ if (callRes.status < 200 || callRes.status >= 300) {
278
+ return errorResult(`HTTP ${callRes.status}`);
279
+ }
280
+ if (parsed === null)
281
+ return errorResult("malformed response");
282
+ const result = parsed.result;
283
+ if (result === undefined || result === null || typeof result !== "object") {
284
+ return errorResult("malformed response");
285
+ }
286
+ // Hand the upstream result back exactly as received.
287
+ return result;
288
+ }
289
+ }
290
+ /** Build a forwarding client; tests inject a fake fetch and env through deps. */
291
+ export function createClient(deps = {}) {
292
+ return new PolyguideClient(deps);
293
+ }
294
+ /** One-shot helper: a fresh client for a single call (the CLI path). */
295
+ export async function callTool(name, args, deps = {}) {
296
+ return new PolyguideClient(deps).callTool(name, args);
297
+ }
298
+ //# sourceMappingURL=forward.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"forward.js","sourceRoot":"","sources":["../src/forward.ts"],"names":[],"mappings":"AAkDA,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC;AAE/B,MAAM,CAAC,MAAM,oBAAoB,GAAG,oDAAoD,CAAC;AAEzF,MAAM,CAAC,MAAM,kBAAkB,GAAG,KAAK,CAAC;AAExC,MAAM,CAAC,MAAM,gBAAgB,GAAG,YAAY,CAAC;AAE7C,wEAAwE;AACxE,yEAAyE;AACzE,yEAAyE;AACzE,wEAAwE;AACxE,yEAAyE;AACzE,wEAAwE;AAExE,MAAM,CAAC,MAAM,SAAS,GAAgB;IAClC;QACE,MAAM,EAAE,cAAc;QACtB,aAAa,EAAE,wOAAwO;QACvP,aAAa,EAAE;YACb,MAAM,EAAE,QAAQ;YAChB,YAAY,EAAE;gBACZ,OAAO,EAAE;oBACP,MAAM,EAAE,QAAQ;oBAChB,aAAa,EAAE,yFAAyF;iBACzG;gBACD,OAAO,EAAE;oBACP,MAAM,EAAE,SAAS;oBACjB,aAAa,EAAE,+CAA+C;iBAC/D;aACF;YACD,UAAU,EAAE;gBACV,OAAO;aACR;SACF;KACF;IACD;QACE,MAAM,EAAE,aAAa;QACrB,aAAa,EAAE,0UAA0U;QACzV,aAAa,EAAE;YACb,MAAM,EAAE,QAAQ;YAChB,YAAY,E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AAC,IAAI,EAAE,IAAI,CAAC,CAAC;AACxD,CAAC"}
@@ -0,0 +1,2 @@
1
+ export * from "./types.js";
2
+ export * from "./forward.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./types.js";
2
+ export * from "./forward.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC"}
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * polyguide MCP server. Tools: the 4 captured subset
3
+ * tools for the LieDetectorTest service (see forward.ts).
4
+ *
5
+ * This file uses the low-level Server API rather than
6
+ * McpServer: the high-level helper rebuilds schemas from
7
+ * zod and rewrites what is served, which would break
8
+ * exact parity with the captured tools/list. Here
9
+ * tools/list is answered locally from the core's literal
10
+ * definitions — the verbatim objects from the upstream
11
+ * capture — and every tools/call is forwarded upstream.
12
+ *
13
+ * A forwarded result returns unchanged, upstream isError
14
+ * flag and extra fields included. An upstream failure
15
+ * arrives as an isError result carrying a
16
+ * `polyguide error:` text, built by the forwarding
17
+ * client. Unknown tool names are rejected with McpError
18
+ * MethodNotFound, and non-object arguments with McpError
19
+ * InvalidParams, before any network hop is made.
20
+ */
21
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
22
+ import { type PolyguideClient } from "./forward.js";
23
+ import type { ForwardDeps, ToolResult } from "./types.js";
24
+ /**
25
+ * Validate and forward a single tools/call through
26
+ * `client`. Exported so this layer can be tested directly
27
+ * without a stdio transport.
28
+ */
29
+ export declare function handleCallTool(client: PolyguideClient, name: string, args: unknown): Promise<ToolResult>;
30
+ /** Build the stdio MCP server (transport not yet connected). */
31
+ export declare function createServer(deps?: ForwardDeps): Server;
32
+ /** Connect the MCP server over stdio. */
33
+ export declare function startMcpServer(deps?: ForwardDeps): Promise<void>;
package/dist/mcp.js ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * polyguide MCP server. Tools: the 4 captured subset
3
+ * tools for the LieDetectorTest service (see forward.ts).
4
+ *
5
+ * This file uses the low-level Server API rather than
6
+ * McpServer: the high-level helper rebuilds schemas from
7
+ * zod and rewrites what is served, which would break
8
+ * exact parity with the captured tools/list. Here
9
+ * tools/list is answered locally from the core's literal
10
+ * definitions — the verbatim objects from the upstream
11
+ * capture — and every tools/call is forwarded upstream.
12
+ *
13
+ * A forwarded result returns unchanged, upstream isError
14
+ * flag and extra fields included. An upstream failure
15
+ * arrives as an isError result carrying a
16
+ * `polyguide error:` text, built by the forwarding
17
+ * client. Unknown tool names are rejected with McpError
18
+ * MethodNotFound, and non-object arguments with McpError
19
+ * InvalidParams, before any network hop is made.
20
+ */
21
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
22
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
23
+ import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError, } from "@modelcontextprotocol/sdk/types.js";
24
+ import { createClient, isKnownTool, TOOL_DEFS, VERSION, } from "./forward.js";
25
+ /**
26
+ * Validate and forward a single tools/call through
27
+ * `client`. Exported so this layer can be tested directly
28
+ * without a stdio transport.
29
+ */
30
+ export async function handleCallTool(client, name, args) {
31
+ if (!isKnownTool(name)) {
32
+ throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
33
+ }
34
+ if (args !== undefined &&
35
+ (typeof args !== "object" || args === null || Array.isArray(args))) {
36
+ throw new McpError(ErrorCode.InvalidParams, `Arguments for tool ${name} must be a JSON object`);
37
+ }
38
+ return client.callTool(name, (args ?? {}));
39
+ }
40
+ /** Build the stdio MCP server (transport not yet connected). */
41
+ export function createServer(deps = {}) {
42
+ const client = createClient(deps);
43
+ const server = new Server({ name: "polyguide", version: VERSION }, { capabilities: { tools: {} } });
44
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
45
+ tools: TOOL_DEFS,
46
+ }));
47
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
48
+ const { name, arguments: args } = request.params;
49
+ const result = await handleCallTool(client, name, args);
50
+ return result;
51
+ });
52
+ return server;
53
+ }
54
+ /** Connect the MCP server over stdio. */
55
+ export async function startMcpServer(deps = {}) {
56
+ await createServer(deps).connect(new StdioServerTransport());
57
+ }
58
+ //# sourceMappingURL=mcp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.js","sourceRoot":"","sources":["../src/mcp.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EACL,qBAAqB,EACrB,SAAS,EACT,sBAAsB,EACtB,QAAQ,GACT,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,YAAY,EACZ,WAAW,EACX,SAAS,EACT,OAAO,GAER,MAAM,cAAc,CAAC;AAGtB;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,MAAuB,EACvB,IAAY,EACZ,IAAa;IAEb,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC;QACvB,MAAM,IAAI,QAAQ,CAAC,SAAS,CAAC,cAAc,EAAE,iBAAiB,IAAI,EAAE,CAAC,CAAC;IACxE,CAAC;IACD,IACE,IAAI,KAAK,SAAS;QAClB,CAAC,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,EAClE,CAAC;QACD,MAAM,IAAI,QAAQ,CAChB,SAAS,CAAC,aAAa,EACvB,sBAAsB,IAAI,wBAAwB,CACnD,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,IAAI,IAAI,EAAE,CAA4B,CAAC,CAAC;AACxE,CAAC;AAED,gEAAgE;AAChE,MAAM,UAAU,YAAY,CAAC,OAAoB,EAAE;IACjD,MAAM,MAAM,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;IAClC,MAAM,MAAM,GAAG,IAAI,MAAM,CACvB,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,EAAE,EACvC,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,CAChC,CAAC;IAEF,MAAM,CAAC,iBAAiB,CAAC,sBAAsB,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC;QAC5D,KAAK,EAAE,SAAS;KACjB,CAAC,CAAC,CAAC;IAEJ,MAAM,CAAC,iBAAiB,CAAC,qBAAqB,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE;QAChE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC;QACjD,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;QACxD,OAAO,MAAe,CAAC;IACzB,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,yCAAyC;AACzC,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,OAAoB,EAAE;IACzD,MAAM,YAAY,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,IAAI,oBAAoB,EAAE,CAAC,CAAC;AAC/D,CAAC"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * polyguide types.
3
+ *
4
+ * This package holds no directory data of its own. It is a
5
+ * forwarding client: the captured subset surface for the
6
+ * LieDetectorTest service is kept as plain data (ToolDef
7
+ * entries served verbatim for tools/list) and each
8
+ * tools/call is sent to the hosted LieDetectorTest MCP
9
+ * endpoint through an injectable fetch, so the whole test
10
+ * suite can run against a stubbed upstream with no live
11
+ * network.
12
+ */
13
+ /** One captured tool definition, served exactly as captured for tools/list. */
14
+ export interface ToolDef {
15
+ name: string;
16
+ title?: string;
17
+ description: string;
18
+ inputSchema: Record<string, unknown>;
19
+ [key: string]: unknown;
20
+ }
21
+ /** Arguments for a tool call, as decoded JSON. */
22
+ export type ToolArgs = Record<string, unknown>;
23
+ /** A tools/call result: upstream payloads pass through verbatim; local failures use this shape too. */
24
+ export interface ToolResult {
25
+ content?: unknown;
26
+ isError?: boolean;
27
+ [key: string]: unknown;
28
+ }
29
+ /** The narrow slice of a fetch Response the forwarding client relies on. */
30
+ export interface FetchResponseLike {
31
+ ok: boolean;
32
+ status: number;
33
+ headers: {
34
+ get(name: string): string | null;
35
+ };
36
+ text(): Promise<string>;
37
+ }
38
+ /** Injectable fetch function, so tests never reach the live network. */
39
+ export type FetchFn = (url: string, init?: {
40
+ method?: string;
41
+ headers?: Record<string, string>;
42
+ body?: string;
43
+ signal?: AbortSignal;
44
+ }) => Promise<FetchResponseLike>;
45
+ /** Injectable runtime dependencies for the forwarding client. */
46
+ export interface ForwardDeps {
47
+ /** Fetch implementation. Defaults to the global fetch. */
48
+ fetchFn?: FetchFn;
49
+ /** Environment (LIEDETECTORTEST_MCP_URL). Defaults to process.env. */
50
+ env?: Record<string, string | undefined>;
51
+ /** Endpoint URL override. Defaults to env LIEDETECTORTEST_MCP_URL or the pinned default. */
52
+ url?: string;
53
+ /** Per-request timeout in milliseconds. Defaults to 30000. */
54
+ timeoutMs?: number;
55
+ }
package/dist/types.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * polyguide types.
3
+ *
4
+ * This package holds no directory data of its own. It is a
5
+ * forwarding client: the captured subset surface for the
6
+ * LieDetectorTest service is kept as plain data (ToolDef
7
+ * entries served verbatim for tools/list) and each
8
+ * tools/call is sent to the hosted LieDetectorTest MCP
9
+ * endpoint through an injectable fetch, so the whole test
10
+ * suite can run against a stubbed upstream with no live
11
+ * network.
12
+ */
13
+ export {};
14
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG"}
package/package.json CHANGED
@@ -1,6 +1 @@
1
- {
2
- "name": "@reneturcios/polyguide",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {"bin":{"polyguide":"dist/cli.js"},"dependencies":{"@modelcontextprotocol/sdk":"^1","zod":"^4"},"description":"Polygraph office directory reads: find offices, published pricing, service info and booking status by reference — forwarded from the hosted LieDetectorTest service. One bin serves a small CLI and the MCP server.","devDependencies":{"@types/node":"^20","tsx":"^4","typescript":"^5"},"engines":{"node":">=20"},"files":["dist","server.json"],"homepage":"https://github.com/CloudCorpRecords/polyguide#readme","license":"MIT","mcpName":"io.github.CloudCorpRecords/polyguide","name":"@reneturcios/polyguide","private":false,"publishConfig":{"access":"public"},"repository":{"type":"git","url":"git+https://github.com/CloudCorpRecords/polyguide.git"},"scripts":{"build":"tsc","dev":"tsx src/cli.ts","test":"tsx --test test/*.test.ts"},"type":"module","version":"0.1.0"}
package/server.json ADDED
@@ -0,0 +1 @@
1
+ {"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","description":"Polygraph office directory: find offices, published pricing and service info by location.","name":"io.github.CloudCorpRecords/polyguide","packages":[{"identifier":"@reneturcios/polyguide","packageArguments":[{"type":"positional","value":"mcp"}],"registryBaseUrl":"https://registry.npmjs.org","registryType":"npm","runtimeHint":"npx","transport":{"type":"stdio"},"version":"0.1.0"},{"identifier":"ghcr.io/cloudcorprecords/polyguide:0.1.0","packageArguments":[{"type":"positional","value":"mcp"}],"registryType":"oci","runtimeArguments":[{"name":"--rm","type":"named"},{"name":"-i","type":"named"}],"runtimeHint":"docker","transport":{"type":"stdio"}}],"repository":{"source":"github","url":"https://github.com/CloudCorpRecords/polyguide"},"version":"0.1.0"}