extract Minecraft tools to shared toolkit; gate Redstone replies to authorized senders

Redstone previously only saw the 23 tg_* tools — it had no idea the
Minecraft stack existed, so questions like "is the server up?" went
unanswered. This change extracts the 15 Minecraft tools (lifecycle,
rcon, backup, players, seen) into the same shared catalog the Telegram
tools already used, so both Gemini and external MCP clients see them.

mcp/lib/types.ts (new) holds the shared shape: Tool<P>, ToolCtx,
createTgClient, createMcRuntime (a Bun.spawn-based wrapper for docker
compose / docker exec), and toolToGeminiFunction (zod → Gemini schema,
now also stripping exclusiveMinimum/Maximum since Gemini rejects them).

mcp/lib/minecraft-tools.ts (new) is the catalog itself. Eight handlers
are flagged requiresAdmin: rcon, backup, and all destructive player_*
writes plus seen_list. mcp/server.ts trusts the caller (Claude / Paul
on the host) and ignores the flag; bot/bot.ts honours it at dispatch
time, returning {error: "...requires admin role..."} to Gemini so it
can explain to the user instead of attempting the call.

mcp/server.ts shrinks from 423 lines to 70 — a single loop over both
catalogs replaces the hand-rolled registrations.

bot/bot.ts wires both catalogs into the function declarations and adds
the admin gate. It also gains a defensive re-check on every incoming
group/DM text: the Redstone handler now does its own lookup of
ctx.from.id against the users table and refuses to reply unless
status='active'. This is belt-and-braces — the auth middleware already
short-circuits unauthorized callers earlier in the chain, but with
privacy-mode-off groups now feeding every message through, a future
refactor that reorders middleware shouldn't be able to make Redstone
respond to strangers.

Drops thinkingConfig from the Gemini call (gemini-2.5-flash-lite
rejects it outright with HTTP 400).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-11 23:19:27 +02:00
parent 875d6fd6dd
commit d22cb73a2c
5 changed files with 467 additions and 489 deletions

View File

@@ -1,52 +1,7 @@
// Shared Telegram-action toolkit.
// Imported by mcp/server.ts (registers each as an MCP tool) and by bot/bot.ts
// (exposes each as a Gemini function declaration and dispatches calls).
// Imports of npm packages resolve via this directory's node_modules (i.e. mcp/node_modules)
// regardless of which process loads the file.
// Telegram tool catalog. Shared types + helpers live in ./types.ts.
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
import type { Database } from "bun:sqlite";
// ---- Telegram HTTP client ----
export type TgClient = {
call: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T>;
};
export function createTgClient(token: string): TgClient {
if (!token) throw new Error("createTgClient: empty token");
const base = `https://api.telegram.org/bot${token}`;
return {
async call<T>(method: string, params: Record<string, unknown> = {}): Promise<T> {
const res = await fetch(`${base}/${method}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(params),
signal: AbortSignal.timeout(20_000),
});
const data = (await res.json()) as { ok: boolean; result?: T; description?: string; error_code?: number };
if (!data.ok) throw new Error(`${method}: ${data.description} (code ${data.error_code})`);
return data.result as T;
},
};
}
// ---- Tool context passed to every handler ----
export type ToolCtx = {
tg: TgClient;
db: Database;
};
// ---- Tool definition shape ----
export type Tool<Params extends z.ZodRawShape = z.ZodRawShape> = {
name: string;
title: string;
description: string;
parameters: Params;
handler: (args: z.infer<z.ZodObject<Params>>, ctx: ToolCtx) => Promise<unknown>;
};
import { tool, type Tool } from "./types.ts";
export { createTgClient, toolToGeminiFunction, type ToolCtx, type Tool, type TgClient } from "./types.ts";
// ---- Shared sub-schemas ----
@@ -83,11 +38,6 @@ function buildKeyboard(rows: z.infer<typeof ButtonSchema>[][] | undefined) {
// ---- The tool catalog ----
// Helper to keep the array strictly typed without losing each tool's specific param shape.
function tool<P extends z.ZodRawShape>(t: Tool<P>): Tool<z.ZodRawShape> {
return t as Tool<z.ZodRawShape>;
}
export const telegramTools: Tool<z.ZodRawShape>[] = [
// ---- discovery ----
tool({
@@ -418,44 +368,3 @@ export const telegramTools: Tool<z.ZodRawShape>[] = [
}),
];
// ---- JSON Schema conversion for Gemini function declarations ----
// Gemini's parameters block accepts a JSON-Schema-ish dialect. zod-to-json-schema
// emits JSON-Schema draft-07; the field shapes we use (string/integer/number/boolean/array/object/enum)
// pass through unchanged. We strip `$schema` since Gemini ignores it.
function cleanForGemini(s: unknown): unknown {
if (Array.isArray(s)) return s.map(cleanForGemini);
if (s && typeof s === "object") {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(s as Record<string, unknown>)) {
if (k === "$schema" || k === "additionalProperties" || k === "default") continue;
// Gemini doesn't accept `union/anyOf` for chat fields — flatten to "string" for compatibility.
if (k === "anyOf" || k === "oneOf") {
// Pick the first non-null subtype heuristically.
const variants = (v as unknown[]).filter((x) => x && (x as Record<string, unknown>).type !== "null");
if (variants.length === 1) return cleanForGemini(variants[0]);
// For mixed types we fall back to string.
return { type: "string" };
}
out[k] = cleanForGemini(v);
}
return out;
}
return s;
}
export function toolToGeminiFunction(t: Tool<z.ZodRawShape>) {
// Gemini's schema dialect rejects $ref/$defs/$schema/additionalProperties, so:
// - $refStrategy "none" inlines shared sub-schemas (e.g. ButtonSchema reused across tools).
// - cleanForGemini strips the rest.
const schema = zodToJsonSchema(z.object(t.parameters), {
$refStrategy: "none",
target: "openApi3",
});
const params = cleanForGemini(schema) as Record<string, unknown>;
return {
name: t.name,
description: t.description,
parameters: params.type ? params : { type: "object", properties: {} },
};
}