@turingcode/cli 0.2.5 → 0.2.7

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
@@ -13,11 +13,17 @@ npm install -g @turingcode/cli
13
13
  | `turingcode contract check --contract c.json` | Validates a contract and the contracts it depends on. |
14
14
  | `turingcode contract describe --contract c.json` | Prints the tables a contract expects, as Markdown (e.g. for a prompt). |
15
15
  | `turingcode table check --contract c.json --tables t.md [--dep alias=file]` | Checks tables against the contract. |
16
+ | `turingcode tool list` | Lists the Turing Code server tools your token can call, one line each. |
17
+ | `turingcode tool describe <name>... [--json]` | Shows the full description and arguments of the named tools (`--json`: raw schemas). |
18
+ | `turingcode tool call <name> [--args json\|file]` | Calls a server tool and prints its text result, e.g. `> result.md` to save it. |
16
19
 
17
20
  Output is compact text: a status line, one line per finding (the same error on several rows is one
18
21
  line), and a fix hint per code. `--json` prints the full result. Exit codes: `0` PASS/VALID,
19
22
  `1` FAIL/INVALID_CONTRACT, `2` bad input or missing file.
20
23
 
24
+ `tool` commands need `TURINGCODE_TOKEN` (gateway token); `TURINGCODE_URL` overrides the gateway.
25
+ They exit `0` on success and `1` on a tool error (printed to stderr) or a failed request.
26
+
21
27
  ## Contract format
22
28
 
23
29
  Every check on cell values is a MongoDB-style query (run with [sift](https://github.com/crcn/sift.js),
@@ -108,7 +114,7 @@ is a value or an operator object. As in MongoDB:
108
114
  | --- | --- |
109
115
  | `$eq` `$ne` `$in` `$nin` | Equal / not equal / one of / none of (text, `true`/`false` or `null`). |
110
116
  | `$regex` `$options` | Regex search; anchor with `^...$` to match the whole value. |
111
- | `$gt` `$gte` `$lt` `$lte` | Exact number comparison (`0.1 + 0.2` is `0.3`); text never matches. |
117
+ | `$gt` `$gte` `$lt` `$lte` | Exact number comparison (`0.1 + 0.2` is `0.3`); text never matches. A `YYYY-MM-DD` bound compares dates instead, e.g. `{"$gte": "2026-01-01"}`; a cell that is not a date never matches. |
112
118
  | `$not` | The condition does not hold. |
113
119
  | `$or` `$and` `$nor` | Combine conditions; allowed in a column's condition too. |
114
120
  | `$ref` | The value exists in `Table.Column` or `alias:Table.Column`. |
@@ -1,8 +1,9 @@
1
1
  import yargs from "yargs/yargs";
2
2
  import contract from "../features/contract/command.js";
3
3
  import table from "../features/table/command.js";
4
+ import tool from "../features/tool/command.js";
4
5
  // The clock commands (../features/clock/command.js) are kept but not registered for now.
5
- const commands = [contract, table];
6
+ const commands = [contract, table, tool];
6
7
  /**
7
8
  * Builds the yargs parser with every feature command registered.
8
9
  *
@@ -14,9 +15,12 @@ export function createCli(args) {
14
15
  .scriptName("turingcode")
15
16
  .usage("Usage: $0 <command> [options]; $0 <command> --help for each command's usage")
16
17
  .epilogue([
17
- "Checks tables written in Markdown or CSV against a contract: a JSON file that declares the tables,",
18
- "their columns, and checks on values and rows as MongoDB-style queries. Contract format: $0 contract --help.",
19
- "Typical use: `contract describe` shows the tables to write; write them; `table check` until PASS.",
18
+ "Turing Code toolkit for AI agents.",
19
+ "- Server tools: `tool list` to find a tool, `tool describe <name>` for its arguments,",
20
+ " `tool call <name> --args ... > file` to run it and save the result (needs TURINGCODE_TOKEN: $0 tool --help).",
21
+ "- Tables: check Markdown or CSV tables against a contract (a JSON file of tables, columns and",
22
+ " MongoDB-style checks): `contract describe` shows the tables to write; `table check` until PASS.",
23
+ " Contract format: $0 contract --help.",
20
24
  ].join("\n"))
21
25
  .command(commands)
22
26
  .demandCommand(1)
@@ -0,0 +1,16 @@
1
+ const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
2
+ /**
3
+ * Whether a text is a real calendar date written `YYYY-MM-DD`. Such dates sort
4
+ * correctly as plain text, so they can be compared without parsing.
5
+ *
6
+ * @param {string} v - The text to test.
7
+ * @returns {boolean} True for a valid date, false otherwise (including `2026-02-30`).
8
+ *
9
+ * @example
10
+ * isDate("2026-02-28"); // true
11
+ * isDate("2026-02-30"); // false
12
+ */
13
+ export function isDate(v) {
14
+ const m = DATE.exec(v);
15
+ return !!m && new Date(Date.UTC(+m[1], +m[2] - 1, +m[3])).toISOString().startsWith(v);
16
+ }
@@ -24,3 +24,19 @@ export function readJsonFile(path) {
24
24
  return { ok: false, error: "bad_json", message: e.message };
25
25
  }
26
26
  }
27
+ /**
28
+ * Reads a JSON flag: inline JSON, or a path to a .json file.
29
+ *
30
+ * @param {string} value - Raw flag value.
31
+ * @returns {unknown} The parsed JSON.
32
+ * @throws {Error} When the file cannot be read or the JSON is invalid.
33
+ */
34
+ export function readJsonArg(value) {
35
+ const text = value.trimStart().startsWith("{") ? value : readFileSync(value, "utf-8");
36
+ try {
37
+ return JSON.parse(text);
38
+ }
39
+ catch (e) {
40
+ throw new Error(`invalid JSON (${e.message})`);
41
+ }
42
+ }
package/dist/core/mcp.js CHANGED
@@ -1,19 +1,27 @@
1
1
  /** Default public MCP gateway (public-mcp-tools in the turingcode repo). */
2
2
  export const DEFAULT_URL = "https://mcp.turingcode.ai/mcp";
3
+ /** Where to put the gateway token; shown in the help of server commands and when the token is missing. */
4
+ export const TOKEN_HELP = [
5
+ "Token: set TURINGCODE_TOKEN to your Turing Code gateway token. To keep it, add",
6
+ "`export TURINGCODE_TOKEN=<token>` to ~/.bashrc or ~/.zshrc and open a new shell",
7
+ "(Windows: `setx TURINGCODE_TOKEN <token>`, then a new terminal). For an AI agent, set it in the",
8
+ "agent's environment settings (e.g. \"env\" in Claude Code's settings.json). Keep it out of repositories.",
9
+ `TURINGCODE_URL overrides the gateway (default ${DEFAULT_URL}).`,
10
+ ].join("\n");
3
11
  /**
4
- * Calls one tool on the Turing Code MCP gateway.
12
+ * Sends one JSON-RPC request to the Turing Code MCP gateway.
5
13
  *
6
- * The gateway is stateless streamable-HTTP, so a single `tools/call` POST
7
- * works without an `initialize` handshake.
14
+ * The gateway is stateless streamable-HTTP, so a single POST works without
15
+ * an `initialize` handshake.
8
16
  *
9
- * @param {string} name - Tool name, e.g. `stm32_cubetools_clock_solve`.
10
- * @param {Record<string, unknown>} args - Tool arguments.
17
+ * @param {string} method - JSON-RPC method, e.g. `tools/call` or `tools/list`.
18
+ * @param {Record<string, unknown>} params - Method params.
11
19
  * @param {string} token - Bearer token for the gateway.
12
20
  * @param {string} [url=DEFAULT_URL] - Gateway endpoint.
13
- * @returns {Promise<ToolResult>} The tool's text content and error flag.
21
+ * @returns {Promise<any>} The reply's `result`.
14
22
  * @throws {Error} On HTTP errors or a JSON-RPC error reply.
15
23
  */
16
- export async function callTool(name, args, token, url = DEFAULT_URL) {
24
+ async function postGateway(method, params, token, url = DEFAULT_URL) {
17
25
  const response = await fetch(url, {
18
26
  method: "POST",
19
27
  headers: {
@@ -21,26 +29,49 @@ export async function callTool(name, args, token, url = DEFAULT_URL) {
21
29
  "Content-Type": "application/json",
22
30
  "Accept": "application/json, text/event-stream",
23
31
  },
24
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
32
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
25
33
  });
26
34
  const body = await response.text();
27
35
  if (!response.ok) {
28
36
  throw new Error(`gateway HTTP ${response.status}: ${body.trim() || response.statusText}`);
29
37
  }
30
- return parseToolReply(body);
38
+ return parseRpcReply(body);
39
+ }
40
+ /**
41
+ * Calls one tool on the Turing Code MCP gateway.
42
+ *
43
+ * @param {string} name - Tool name, e.g. `stm32_cubetools_clock_solve`.
44
+ * @param {Record<string, unknown>} args - Tool arguments.
45
+ * @param {string} token - Bearer token for the gateway.
46
+ * @param {string} [url=DEFAULT_URL] - Gateway endpoint.
47
+ * @returns {Promise<ToolResult>} The tool's text content and error flag.
48
+ * @throws {Error} On HTTP errors or a JSON-RPC error reply.
49
+ */
50
+ export async function callTool(name, args, token, url = DEFAULT_URL) {
51
+ return toToolResult(await postGateway("tools/call", { name, arguments: args }, token, url));
52
+ }
53
+ /**
54
+ * Lists the tools the gateway token can reach (the gateway applies its allow/deny policy).
55
+ *
56
+ * @param {string} token - Bearer token for the gateway.
57
+ * @param {string} [url=DEFAULT_URL] - Gateway endpoint.
58
+ * @returns {Promise<ToolInfo[]>} Name, description and input schema of each tool.
59
+ * @throws {Error} On HTTP errors or a JSON-RPC error reply.
60
+ */
61
+ export async function listTools(token, url = DEFAULT_URL) {
62
+ return (await postGateway("tools/list", {}, token, url))?.tools ?? [];
31
63
  }
32
64
  /**
33
- * Turns a gateway reply (plain JSON or an SSE stream) into a ToolResult.
65
+ * Extracts the JSON-RPC `result` from a gateway reply (plain JSON or an SSE stream).
34
66
  *
35
67
  * @param {string} body - Raw response body.
36
- * @returns {ToolResult} The joined text content and error flag.
68
+ * @returns {any} The reply's `result`.
37
69
  * @throws {Error} When the reply holds no JSON-RPC response or carries an error.
38
70
  *
39
71
  * @example
40
- * parseToolReply('data: {"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"ok"}]}}');
41
- * // { text: "ok", isError: false }
72
+ * parseRpcReply('data: {"jsonrpc":"2.0","id":1,"result":{"tools":[]}}'); // { tools: [] }
42
73
  */
43
- export function parseToolReply(body) {
74
+ export function parseRpcReply(body) {
44
75
  const payloads = body.trimStart().startsWith("{")
45
76
  ? [body]
46
77
  : body.split("\n").filter(line => line.startsWith("data:")).map(line => line.slice(5));
@@ -51,12 +82,48 @@ export function parseToolReply(body) {
51
82
  if (reply.error) {
52
83
  throw new Error(`gateway error ${reply.error.code}: ${reply.error.message}`);
53
84
  }
54
- const content = reply.result?.content ?? [];
85
+ return reply.result;
86
+ }
87
+ /**
88
+ * Joins a `tools/call` result's text content.
89
+ *
90
+ * @param {any} result - The JSON-RPC result of `tools/call`.
91
+ * @returns {ToolResult} The joined text content and error flag.
92
+ */
93
+ function toToolResult(result) {
94
+ const content = result?.content ?? [];
55
95
  return {
56
96
  text: content.filter(c => c.type === "text").map(c => c.text).join("\n"),
57
- isError: Boolean(reply.result?.isError),
97
+ isError: Boolean(result?.isError),
58
98
  };
59
99
  }
100
+ /**
101
+ * Turns a gateway `tools/call` reply (plain JSON or an SSE stream) into a ToolResult.
102
+ *
103
+ * @param {string} body - Raw response body.
104
+ * @returns {ToolResult} The joined text content and error flag.
105
+ * @throws {Error} When the reply holds no JSON-RPC response or carries an error.
106
+ *
107
+ * @example
108
+ * parseToolReply('data: {"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"ok"}]}}');
109
+ * // { text: "ok", isError: false }
110
+ */
111
+ export function parseToolReply(body) {
112
+ return toToolResult(parseRpcReply(body));
113
+ }
114
+ /**
115
+ * Reads the gateway token and endpoint from TURINGCODE_TOKEN and TURINGCODE_URL.
116
+ *
117
+ * @returns {{token: string, url: string}} The token and gateway URL.
118
+ * @throws {Error} When TURINGCODE_TOKEN is not set.
119
+ */
120
+ export function getGatewayConfig() {
121
+ const token = process.env.TURINGCODE_TOKEN?.trim();
122
+ if (!token) {
123
+ throw new Error(`TURINGCODE_TOKEN is not set.\n${TOKEN_HELP}`);
124
+ }
125
+ return { token, url: process.env.TURINGCODE_URL || DEFAULT_URL };
126
+ }
60
127
  /**
61
128
  * Runs a server command: calls the tool with the gateway token from
62
129
  * TURINGCODE_TOKEN and prints its text; a tool error sets exit code 1.
@@ -67,12 +134,9 @@ export function parseToolReply(body) {
67
134
  * @throws {Error} When TURINGCODE_TOKEN is not set, or the gateway call fails.
68
135
  */
69
136
  export async function runServerTool(name, args) {
70
- const token = process.env.TURINGCODE_TOKEN?.trim();
71
- if (!token) {
72
- throw new Error("set TURINGCODE_TOKEN to your Turing Code gateway token");
73
- }
137
+ const { token, url } = getGatewayConfig();
74
138
  const given = Object.fromEntries(Object.entries(args).filter(([, v]) => v !== undefined));
75
- const result = await callTool(name, given, token, process.env.TURINGCODE_URL || DEFAULT_URL);
139
+ const result = await callTool(name, given, token, url);
76
140
  (result.isError ? process.stderr : process.stdout).write(result.text + "\n");
77
141
  if (result.isError) {
78
142
  process.exitCode = 1;
@@ -1,4 +1,5 @@
1
1
  import sift from "sift";
2
+ import { isDate } from "./date.js";
2
3
  import { Fraction } from "./exact/fraction.js";
3
4
  const { $and, $eq, $in, $ne, $nin, $nor, $not, $options, $or, $regex, createEqualsOperation, createQueryTester } = sift;
4
5
  /** Operators on one column's value. */
@@ -49,8 +50,9 @@ export function prepareQuery(query) {
49
50
  out[op] = arg;
50
51
  }
51
52
  else if (NUMERIC.has(op)) {
52
- if (!(typeof arg === "number" || typeof arg === "string") || !Fraction.parseDecimal(String(arg)))
53
- problem(here, "must be a number");
53
+ const ok = typeof arg === "number" || (typeof arg === "string" && (!!Fraction.parseDecimal(arg) || isDate(arg)));
54
+ if (!ok)
55
+ problem(here, "must be a number or a date YYYY-MM-DD");
54
56
  out[op] = arg;
55
57
  }
56
58
  else if (op === "$regex") {
@@ -164,8 +166,15 @@ export function prepareQuery(query) {
164
166
  }
165
167
  /** The whole list when sift passes one of its items (it walks arrays item by item), else the value. */
166
168
  const whole = (v, key, owner) => (typeof key === "number" && Array.isArray(owner) ? owner : v);
167
- /** Exact comparison of a number cell with a bound; anything that is not a number does not match. */
168
- const numeric = (holds) => (bound, owner, options) => {
169
+ /**
170
+ * Exact comparison of a cell with a bound: a `YYYY-MM-DD` bound compares date
171
+ * cells as text (such dates sort as text), any other bound compares number
172
+ * cells exactly. A cell of the other kind does not match.
173
+ */
174
+ const ordered = (holds) => (bound, owner, options) => {
175
+ if (typeof bound === "string" && isDate(bound)) {
176
+ return createEqualsOperation((v) => typeof v === "string" && isDate(v) && holds(v < bound ? -1 : v > bound ? 1 : 0), owner, options);
177
+ }
169
178
  const b = Fraction.parseDecimal(String(bound));
170
179
  return createEqualsOperation((v) => {
171
180
  const n = typeof v === "string" ? Fraction.parseDecimal(v) : null;
@@ -188,7 +197,7 @@ export function compileQuery(query, hooks) {
188
197
  const eq = (test) => (owner, options) => createEqualsOperation(test, owner, options);
189
198
  const operations = {
190
199
  $and, $eq, $in, $ne, $nin, $nor, $not, $options, $or, $regex,
191
- $gt: numeric(c => c > 0), $gte: numeric(c => c >= 0), $lt: numeric(c => c < 0), $lte: numeric(c => c <= 0),
200
+ $gt: ordered(c => c > 0), $gte: ordered(c => c >= 0), $lt: ordered(c => c < 0), $lte: ordered(c => c <= 0),
192
201
  $ref: (ref, o, opt) => eq(v => typeof v === "string" && hooks.ref(ref, v))(o, opt),
193
202
  $mentioned: (targets, o, opt) => eq(v => typeof v === "string" && hooks.mentioned(targets, v))(o, opt),
194
203
  $calc: (param, o, opt) => eq(v => hooks.calc(param, v))(o, opt),
@@ -1,21 +1,5 @@
1
- import { readFileSync } from "node:fs";
1
+ import { readJsonArg } from "../../core/files.js";
2
2
  import { runServerTool } from "../../core/mcp.js";
3
- /**
4
- * Reads a JSON flag: inline JSON, or a path to a .json file.
5
- *
6
- * @param {string} value - Raw flag value.
7
- * @returns {unknown} The parsed JSON.
8
- * @throws {Error} When the file cannot be read or the JSON is invalid.
9
- */
10
- export function readJsonArg(value) {
11
- const text = value.trimStart().startsWith("{") ? value : readFileSync(value, "utf-8");
12
- try {
13
- return JSON.parse(text);
14
- }
15
- catch (e) {
16
- throw new Error(`invalid JSON (${e.message})`);
17
- }
18
- }
19
3
  /**
20
4
  * Rejects number flags that yargs parsed to NaN.
21
5
  *
@@ -44,7 +44,7 @@ Queries are MongoDB syntax: cells are text, an empty cell is null, a list is an
44
44
  (split on "separator", trimmed; an operator matches if any item does, so {"$eq": "x"} means "has item x"
45
45
  and {"$ne": "x"} means "no item is x"). Operators:
46
46
  $eq $ne $in $nin $not $regex $options $or $and $nor (also inside a column's condition)
47
- $gt $gte $lt $lte exact number comparison
47
+ $gt $gte $lt $lte exact number comparison, or date comparison with a "YYYY-MM-DD" bound
48
48
  $ref "Table.Column" value exists there (or "alias:Table.Column" of a dependency)
49
49
  $every {...} every list item meets the condition
50
50
  $length {...} length (chars, or list items) meets the condition
@@ -1,4 +1,5 @@
1
1
  import { BoundError } from "../../core/bound-error.js";
2
+ import { isDate } from "../../core/date.js";
2
3
  import { Fraction } from "../../core/exact/fraction.js";
3
4
  import { compileQuery, prepareQuery } from "../../core/query.js";
4
5
  import { diag, formatDiagnostics, sortDiagnostics } from "../contract/diagnostics.js";
@@ -6,7 +7,6 @@ import { loadContract, parseRef, parseTableRef } from "../contract/load.js";
6
7
  import { keyColumns } from "../contract/model.js";
7
8
  import { evaluateCalc, explain, listItems, mentions, numberColumns, parseCalc, renderCondition, splitQuery, } from "../contract/rules.js";
8
9
  import { readTables } from "./read.js";
9
- const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
10
10
  const plain = (v) => String(v);
11
11
  /**
12
12
  * Why a value does not fit its column's type, or null when it fits.
@@ -23,11 +23,8 @@ function typeProblem(v, col) {
23
23
  return Fraction.parseDecimal(v) ? null : "a number";
24
24
  case "boolean":
25
25
  return v === "true" || v === "false" ? null : "true or false";
26
- case "date": {
27
- const m = DATE.exec(v);
28
- const ok = m && new Date(Date.UTC(+m[1], +m[2] - 1, +m[3])).toISOString().startsWith(v);
29
- return ok ? null : "a date YYYY-MM-DD";
30
- }
26
+ case "date":
27
+ return isDate(v) ? null : "a date YYYY-MM-DD";
31
28
  default:
32
29
  return null;
33
30
  }
@@ -0,0 +1,150 @@
1
+ import { readJsonArg } from "../../core/files.js";
2
+ import { getGatewayConfig, listTools, runServerTool, TOKEN_HELP } from "../../core/mcp.js";
3
+ import { JSON_FLAG } from "../contract/command.js";
4
+ /**
5
+ * Names a JSON schema's type compactly: `string`, `integer | null`, `list of string`, `"a" | "b"`, ...
6
+ *
7
+ * @param {JsonSchema} schema - One property's schema.
8
+ * @returns {string} The type, `any` when the schema gives none.
9
+ *
10
+ * @example
11
+ * schemaType({ anyOf: [{ type: "string" }, { type: "null" }] }); // "string | null"
12
+ */
13
+ function schemaType(schema) {
14
+ if (schema.enum)
15
+ return schema.enum.map(v => JSON.stringify(v)).join(" | ");
16
+ if (schema.anyOf)
17
+ return schema.anyOf.map(schemaType).join(" | ");
18
+ if (schema.$ref)
19
+ return schema.$ref.split("/").at(-1);
20
+ if (schema.type === "array" && schema.items)
21
+ return `list of ${schemaType(schema.items)}`;
22
+ return [schema.type ?? "any"].flat().join(" | ");
23
+ }
24
+ /**
25
+ * Formats tools as one line each: name, then the first line of its description.
26
+ *
27
+ * @param {ToolInfo[]} tools - Tools from the gateway.
28
+ * @returns {string} The text, ending in a newline (empty for no tools).
29
+ *
30
+ * @example
31
+ * formatToolSummaries([{ name: "read_file", description: "Reads a file.\nMore." }]); // "read_file Reads a file.\n"
32
+ */
33
+ export function formatToolSummaries(tools) {
34
+ const width = Math.max(0, ...tools.map(t => t.name.length));
35
+ return tools.map(t => `${t.name.padEnd(width)} ${t.description?.trim().split("\n")[0] ?? ""}`.trimEnd() + "\n").join("");
36
+ }
37
+ /**
38
+ * Formats tools with their full description and arguments, one `## <name>` section per tool.
39
+ *
40
+ * @param {ToolInfo[]} tools - Tools from the gateway.
41
+ * @returns {string} The text, ending in a newline (empty for no tools).
42
+ *
43
+ * @example
44
+ * formatToolDetails([{ name: "read_file", description: "Reads a file.",
45
+ * inputSchema: { properties: { path: { type: "string" } }, required: ["path"] } }]);
46
+ * // "## read_file\n\nReads a file.\n\nArguments:\n- path (string, required)\n"
47
+ */
48
+ export function formatToolDetails(tools) {
49
+ return tools.map(tool => {
50
+ const schema = (tool.inputSchema ?? {});
51
+ const args = Object.entries(schema.properties ?? {}).map(([name, prop]) => {
52
+ const facts = [schemaType(prop), schema.required?.includes(name) ? "required" : undefined,
53
+ prop.default !== undefined ? `default ${JSON.stringify(prop.default)}` : undefined].filter(Boolean);
54
+ return `- ${name} (${facts.join(", ")})${prop.description ? `: ${prop.description.trim()}` : ""}`;
55
+ });
56
+ return [`## ${tool.name}`, tool.description?.trim(), args.length ? `Arguments:\n${args.join("\n")}` : "Arguments: none"]
57
+ .filter(Boolean).join("\n\n") + "\n";
58
+ }).join("\n");
59
+ }
60
+ /**
61
+ * Picks the named tools, in the order given.
62
+ *
63
+ * @param {ToolInfo[]} tools - Tools from the gateway.
64
+ * @param {string[]} names - Tool names to pick.
65
+ * @returns {ToolInfo[]} The named tools.
66
+ * @throws {Error} When a name is not among the tools.
67
+ */
68
+ export function pickTools(tools, names) {
69
+ const unknown = names.filter(name => !tools.some(t => t.name === name));
70
+ if (unknown.length) {
71
+ throw new Error(`unknown tool ${unknown.map(n => `'${n}'`).join(", ")}; \`tool list\` shows the tools you can call`);
72
+ }
73
+ return names.map(name => tools.find(t => t.name === name));
74
+ }
75
+ const list = {
76
+ command: "list",
77
+ describe: "List the server tools your gateway token can call, one line each",
78
+ builder: cli => cli
79
+ .example("$0 tool list", "each tool: name and the first line of its description")
80
+ .epilogue([
81
+ "Prints the tools of the Turing Code server that your token may call, one line each: the name",
82
+ "and the first line of its description. The list comes from the server, so it is always current.",
83
+ "`tool describe <name>` shows a tool's full description and arguments, before `tool call`.",
84
+ "Exit: 0 ok, 1 failed request.",
85
+ TOKEN_HELP,
86
+ ].join("\n")),
87
+ handler: async () => {
88
+ const { token, url } = getGatewayConfig();
89
+ process.stdout.write(formatToolSummaries(await listTools(token, url)));
90
+ },
91
+ };
92
+ const describe = {
93
+ command: "describe <names..>",
94
+ describe: "Show the full description and arguments of the named server tools",
95
+ builder: cli => cli
96
+ .positional("names", { type: "string", array: true, describe: "One or more tool names, from `tool list`" })
97
+ .options({ json: { ...JSON_FLAG, describe: "Print the tools as one-line JSON, with the raw input schemas" } })
98
+ .example("$0 tool describe <name>", "one tool")
99
+ .example("$0 tool describe <name> <other name>", "several tools")
100
+ .epilogue([
101
+ "Prints each named tool as a `## <name>` section: its full description and its arguments",
102
+ "(type, required, default, description), which go in `tool call <name> --args`.",
103
+ "Exit: 0 ok, 1 unknown tool name or failed request.",
104
+ TOKEN_HELP,
105
+ ].join("\n")),
106
+ handler: async (args) => {
107
+ const { token, url } = getGatewayConfig();
108
+ const tools = pickTools(await listTools(token, url), args.names);
109
+ process.stdout.write(args.json ? JSON.stringify(tools) + "\n" : formatToolDetails(tools));
110
+ },
111
+ };
112
+ const call = {
113
+ command: "call <name>",
114
+ describe: "Call a server tool and print its text result (redirect it to save it in a file)",
115
+ builder: cli => cli
116
+ .positional("name", { type: "string", describe: "Tool name, from `tool list`" })
117
+ .options({ args: { type: "string", coerce: readJsonArg, describe: "Tool arguments: inline JSON object or .json path" } })
118
+ .check(argv => {
119
+ const value = argv.args;
120
+ if (value !== undefined && (typeof value !== "object" || value === null || Array.isArray(value))) {
121
+ throw new Error("--args must be a JSON object");
122
+ }
123
+ return true;
124
+ })
125
+ .example(`$0 tool call <name> --args '{"<arg>":"<value>"}'`, "inline arguments, result printed")
126
+ .example("$0 tool call <name> --args args.json > result.md", "arguments from a file, result saved to a file")
127
+ .epilogue([
128
+ "Calls one tool of the Turing Code server. <name> comes from `tool list`, its arguments from",
129
+ "`tool describe <name>`.",
130
+ "--args is a JSON object: inline when it starts with `{`,",
131
+ "otherwise a path to a .json file; leave it out for a tool without arguments.",
132
+ "The tool's text result goes to stdout: redirect it (`> file`) to save a large result without",
133
+ "reading it. A tool error is printed to stderr.",
134
+ "Exit: 0 ok, 1 tool error or failed request.",
135
+ TOKEN_HELP,
136
+ ].join("\n")),
137
+ handler: args => runServerTool(args.name, (args.args ?? {})),
138
+ };
139
+ const command = {
140
+ command: "tool",
141
+ describe: "List, describe or call tools on the Turing Code server",
142
+ builder: cli => cli.command(list).command(describe).command(call).demandCommand(1)
143
+ .epilogue([
144
+ "Typical use: `tool list` to find a tool, `tool describe <name>` for its arguments, then",
145
+ "`tool call <name> --args ... > file` to save its result.",
146
+ TOKEN_HELP,
147
+ ].join("\n")),
148
+ handler: () => { },
149
+ };
150
+ export default command;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turingcode/cli",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "description": "Turing Code toolkit for AI agents: check Markdown/CSV tables against table contracts, e.g. `turingcode table check`.",
5
5
  "type": "module",
6
6
  "bin": {