askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
object_mcp.py · 30.3 KB · 753 lines
| 1 | """MCP (Model Context Protocol) surface for the DBBASIC object server. |
| 2 | |
| 3 | This module holds the protocol constants, the tool catalog, and the mapping |
| 4 | from tool calls to internal HTTP routes. The server dispatches each tool call |
| 5 | back through its own routing with the caller's original credentials, so MCP |
| 6 | tools inherit exactly the same gates, permission checks, audit trail, and |
| 7 | correlation ids as the admin HTTP surface. Nothing new runs underneath. |
| 8 | |
| 9 | Protocol: JSON-RPC 2.0 over HTTP POST, MCP Streamable HTTP transport. |
| 10 | """ |
| 11 | |
| 12 | from __future__ import annotations |
| 13 | |
| 14 | import json |
| 15 | import urllib.parse |
| 16 | from typing import Any, Mapping |
| 17 | |
| 18 | MCP_PROTOCOL_VERSION = "2025-03-26" |
| 19 | SUPPORTED_MCP_PROTOCOL_VERSIONS = frozenset( |
| 20 | { |
| 21 | "2024-11-05", |
| 22 | "2025-03-26", |
| 23 | "2025-11-25", |
| 24 | } |
| 25 | ) |
| 26 | SERVER_INFO = { |
| 27 | "name": "dbbasic-object-server-mcp", |
| 28 | "version": "1.0.0", |
| 29 | } |
| 30 | |
| 31 | _OBJECT_ID_ARG = {"type": "string", "description": "Object id, like site_home"} |
| 32 | _COLLECTION_ARG = {"type": "string", "description": "Collection name, like contacts"} |
| 33 | _RECORD_ID_ARG = {"type": "string", "description": "Record id"} |
| 34 | _LIMIT_ARG = {"type": "integer", "description": "Max rows (default 100)", "default": 100} |
| 35 | |
| 36 | TOOLS: list[dict[str, Any]] = [ |
| 37 | { |
| 38 | "name": "get_admin_status", |
| 39 | "description": "Server health, inventory, capability flags, package posture, and permission readiness", |
| 40 | "inputSchema": {"type": "object", "properties": {}}, |
| 41 | }, |
| 42 | { |
| 43 | "name": "list_objects", |
| 44 | "description": "List all objects with source metadata", |
| 45 | "inputSchema": {"type": "object", "properties": {}}, |
| 46 | }, |
| 47 | { |
| 48 | "name": "get_object_source", |
| 49 | "description": "Read one object's Python source", |
| 50 | "inputSchema": { |
| 51 | "type": "object", |
| 52 | "properties": {"object_id": _OBJECT_ID_ARG}, |
| 53 | "required": ["object_id"], |
| 54 | }, |
| 55 | }, |
| 56 | { |
| 57 | "name": "get_object_state", |
| 58 | "description": "Read one object's persistent state", |
| 59 | "inputSchema": { |
| 60 | "type": "object", |
| 61 | "properties": {"object_id": _OBJECT_ID_ARG}, |
| 62 | "required": ["object_id"], |
| 63 | }, |
| 64 | }, |
| 65 | { |
| 66 | "name": "get_object_logs", |
| 67 | "description": "Read one object's recent log entries", |
| 68 | "inputSchema": { |
| 69 | "type": "object", |
| 70 | "properties": {"object_id": _OBJECT_ID_ARG, "limit": _LIMIT_ARG}, |
| 71 | "required": ["object_id"], |
| 72 | }, |
| 73 | }, |
| 74 | { |
| 75 | "name": "get_object_metadata", |
| 76 | "description": "Read one object's metadata summary", |
| 77 | "inputSchema": { |
| 78 | "type": "object", |
| 79 | "properties": {"object_id": _OBJECT_ID_ARG}, |
| 80 | "required": ["object_id"], |
| 81 | }, |
| 82 | }, |
| 83 | { |
| 84 | "name": "get_object_changes", |
| 85 | "description": "Read one object's source and file change timeline", |
| 86 | "inputSchema": { |
| 87 | "type": "object", |
| 88 | "properties": {"object_id": _OBJECT_ID_ARG, "limit": _LIMIT_ARG}, |
| 89 | "required": ["object_id"], |
| 90 | }, |
| 91 | }, |
| 92 | { |
| 93 | "name": "create_object", |
| 94 | "description": "Create a new object from Python source (requires source writes enabled)", |
| 95 | "inputSchema": { |
| 96 | "type": "object", |
| 97 | "properties": { |
| 98 | "object_id": _OBJECT_ID_ARG, |
| 99 | "code": {"type": "string", "description": "Python source with GET/POST/PUT/DELETE methods"}, |
| 100 | "message": {"type": "string", "description": "Change message"}, |
| 101 | }, |
| 102 | "required": ["object_id", "code"], |
| 103 | }, |
| 104 | }, |
| 105 | { |
| 106 | "name": "update_object_source", |
| 107 | "description": "Replace one object's source; saves a version and change history (requires source writes enabled)", |
| 108 | "inputSchema": { |
| 109 | "type": "object", |
| 110 | "properties": { |
| 111 | "object_id": _OBJECT_ID_ARG, |
| 112 | "code": {"type": "string", "description": "New Python source"}, |
| 113 | "message": {"type": "string", "description": "Change message"}, |
| 114 | }, |
| 115 | "required": ["object_id", "code"], |
| 116 | }, |
| 117 | }, |
| 118 | { |
| 119 | "name": "execute_object", |
| 120 | "description": "Run one object method and return its response, like a request would", |
| 121 | "inputSchema": { |
| 122 | "type": "object", |
| 123 | "properties": { |
| 124 | "object_id": _OBJECT_ID_ARG, |
| 125 | "method": { |
| 126 | "type": "string", |
| 127 | "enum": ["GET", "POST", "PUT", "DELETE"], |
| 128 | "default": "GET", |
| 129 | }, |
| 130 | "payload": {"type": "object", "description": "Request payload for the object"}, |
| 131 | }, |
| 132 | "required": ["object_id"], |
| 133 | }, |
| 134 | }, |
| 135 | { |
| 136 | "name": "list_collections", |
| 137 | "description": "List collections with record, schema, and permission summaries", |
| 138 | "inputSchema": {"type": "object", "properties": {}}, |
| 139 | }, |
| 140 | { |
| 141 | "name": "list_records", |
| 142 | "description": ("List records in one collection, optionally filtered. The response carries a `revs` map (record id -> _rev) alongside `records`: pass one back as If-Match on update_record to claim a row safely against another agent doing the same thing."), |
| 143 | "inputSchema": { |
| 144 | "type": "object", |
| 145 | "properties": { |
| 146 | "collection": _COLLECTION_ARG, |
| 147 | "limit": _LIMIT_ARG, |
| 148 | "offset": {"type": "integer", "default": 0}, |
| 149 | "where": { |
| 150 | "type": "object", |
| 151 | "description": ( |
| 152 | "Field filter, ANDed: {field: value} for equality, or " |
| 153 | "{field: {\"op\": op, \"value\": value}} for " |
| 154 | "ne/in/gte/lte/gt/lt. `in`'s value is a list. Only " |
| 155 | "fields you may read are filterable." |
| 156 | ), |
| 157 | }, |
| 158 | }, |
| 159 | "required": ["collection"], |
| 160 | }, |
| 161 | }, |
| 162 | { |
| 163 | "name": "get_record", |
| 164 | "description": "Read one record", |
| 165 | "inputSchema": { |
| 166 | "type": "object", |
| 167 | "properties": {"collection": _COLLECTION_ARG, "record_id": _RECORD_ID_ARG}, |
| 168 | "required": ["collection", "record_id"], |
| 169 | }, |
| 170 | }, |
| 171 | { |
| 172 | "name": "create_record", |
| 173 | "description": "Create one record (validated against the collection schema)", |
| 174 | "inputSchema": { |
| 175 | "type": "object", |
| 176 | "properties": { |
| 177 | "collection": _COLLECTION_ARG, |
| 178 | "record": {"type": "object", "description": "Record fields including id"}, |
| 179 | }, |
| 180 | "required": ["collection", "record"], |
| 181 | }, |
| 182 | }, |
| 183 | { |
| 184 | "name": "update_record", |
| 185 | "description": "Update fields on one record", |
| 186 | "inputSchema": { |
| 187 | "type": "object", |
| 188 | "properties": { |
| 189 | "collection": _COLLECTION_ARG, |
| 190 | "record_id": _RECORD_ID_ARG, |
| 191 | "changes": {"type": "object", "description": "Fields to change"}, |
| 192 | "expected_rev": { |
| 193 | "type": "string", |
| 194 | "description": ( |
| 195 | "Optional optimistic-concurrency precondition: the " |
| 196 | "`_rev` returned by a prior get_record. The update " |
| 197 | "succeeds only if the record still matches it, else " |
| 198 | "409 (63). Omit for last-write-wins." |
| 199 | ), |
| 200 | }, |
| 201 | }, |
| 202 | "required": ["collection", "record_id", "changes"], |
| 203 | }, |
| 204 | }, |
| 205 | { |
| 206 | "name": "delete_record", |
| 207 | "description": "Delete one record", |
| 208 | "inputSchema": { |
| 209 | "type": "object", |
| 210 | "properties": {"collection": _COLLECTION_ARG, "record_id": _RECORD_ID_ARG}, |
| 211 | "required": ["collection", "record_id"], |
| 212 | }, |
| 213 | }, |
| 214 | { |
| 215 | "name": "get_schema", |
| 216 | "description": "Read one collection schema", |
| 217 | "inputSchema": { |
| 218 | "type": "object", |
| 219 | "properties": {"collection": _COLLECTION_ARG}, |
| 220 | "required": ["collection"], |
| 221 | }, |
| 222 | }, |
| 223 | { |
| 224 | "name": "update_schema", |
| 225 | "description": "Replace one collection schema; records a schema version", |
| 226 | "inputSchema": { |
| 227 | "type": "object", |
| 228 | "properties": { |
| 229 | "collection": _COLLECTION_ARG, |
| 230 | "schema": {"type": "object", "description": "Schema payload with fields list"}, |
| 231 | "message": {"type": "string", "description": "Change message"}, |
| 232 | }, |
| 233 | "required": ["collection", "schema"], |
| 234 | }, |
| 235 | }, |
| 236 | { |
| 237 | "name": "rollback_schema", |
| 238 | "description": "Roll one collection schema back to a previous version", |
| 239 | "inputSchema": { |
| 240 | "type": "object", |
| 241 | "properties": { |
| 242 | "collection": _COLLECTION_ARG, |
| 243 | "version_id": {"type": "integer", "description": "Schema version to restore"}, |
| 244 | }, |
| 245 | "required": ["collection", "version_id"], |
| 246 | }, |
| 247 | }, |
| 248 | { |
| 249 | "name": "global_search", |
| 250 | "description": "Search records across all collections whose schema declares search fields", |
| 251 | "inputSchema": { |
| 252 | "type": "object", |
| 253 | "properties": { |
| 254 | "query": {"type": "string", "description": "Search terms; all must match"}, |
| 255 | "limit": {"type": "integer", "description": "Max results per collection", "default": 10}, |
| 256 | "collections": { |
| 257 | "type": "array", |
| 258 | "items": {"type": "string"}, |
| 259 | "description": "Optional collection names to restrict the search to", |
| 260 | }, |
| 261 | }, |
| 262 | "required": ["query"], |
| 263 | }, |
| 264 | }, |
| 265 | { |
| 266 | "name": "list_ops_events", |
| 267 | "description": "Recent operational events: object execution errors and auth activity (login/logout/session mints)", |
| 268 | "inputSchema": { |
| 269 | "type": "object", |
| 270 | "properties": { |
| 271 | "limit": _LIMIT_ARG, |
| 272 | "kind": {"type": "string", "enum": ["execution_error", "auth"]}, |
| 273 | "event": {"type": "string", "description": "Auth event filter, like login_failed"}, |
| 274 | }, |
| 275 | }, |
| 276 | }, |
| 277 | { |
| 278 | "name": "list_changes", |
| 279 | "description": "Unified source/file/record/package change history, filterable", |
| 280 | "inputSchema": { |
| 281 | "type": "object", |
| 282 | "properties": { |
| 283 | "limit": _LIMIT_ARG, |
| 284 | "kind": {"type": "string", "enum": ["source", "file", "record", "package"]}, |
| 285 | "object_id": {"type": "string"}, |
| 286 | "collection": {"type": "string"}, |
| 287 | }, |
| 288 | }, |
| 289 | }, |
| 290 | { |
| 291 | "name": "start_timer", |
| 292 | "description": ( |
| 293 | "Start a time log for the caller (62 - Timer). Auto-stops the " |
| 294 | "caller's already-running timer first, if any, stamping its " |
| 295 | "duration_seconds -- at most one running timer per owner is " |
| 296 | "server-enforced, never a client promise." |
| 297 | ), |
| 298 | "inputSchema": { |
| 299 | "type": "object", |
| 300 | "properties": { |
| 301 | "task_id": {"type": "string", "description": "Optional task this time log is against"}, |
| 302 | "notes": {"type": "string", "description": "Optional notes for the new time log"}, |
| 303 | }, |
| 304 | }, |
| 305 | }, |
| 306 | { |
| 307 | "name": "stop_timer", |
| 308 | "description": ( |
| 309 | "Stop the caller's running timer (62 - Timer): the caller's " |
| 310 | "current running time log by default, or a specific " |
| 311 | "time_log_id if it belongs to the caller. Stamps " |
| 312 | "duration_seconds = floor(ended_at - started_at). 409 if " |
| 313 | "there is no running timer to stop, 403 if the named timer " |
| 314 | "belongs to another owner." |
| 315 | ), |
| 316 | "inputSchema": { |
| 317 | "type": "object", |
| 318 | "properties": { |
| 319 | "time_log_id": { |
| 320 | "type": "string", |
| 321 | "description": "Optional; defaults to the caller's currently running timer", |
| 322 | }, |
| 323 | }, |
| 324 | }, |
| 325 | }, |
| 326 | { |
| 327 | "name": "get_running_timer", |
| 328 | "description": "Return the caller's currently running time log (62 - Timer), or null", |
| 329 | "inputSchema": {"type": "object", "properties": {}}, |
| 330 | }, |
| 331 | { |
| 332 | "name": "setup_finance_accounts", |
| 333 | "description": ( |
| 334 | "Seed one of the caller's entities with a chart of accounts based " |
| 335 | "on its mode (65 multi-entity): simple = income + expenses, " |
| 336 | "standard = a 15-account chart, double_entry = a full 29-account " |
| 337 | "chart. Idempotent -- accounts already present (by name) are " |
| 338 | "skipped. The entity must belong to the caller." |
| 339 | ), |
| 340 | "inputSchema": { |
| 341 | "type": "object", |
| 342 | "properties": { |
| 343 | "entity_id": {"type": "string", "description": "The entity (set of books) to set up accounts for"}, |
| 344 | }, |
| 345 | "required": ["entity_id"], |
| 346 | }, |
| 347 | }, |
| 348 | { |
| 349 | "name": "get_feed", |
| 350 | "description": ( |
| 351 | "64 - Feed: recent PUBLIC content from accounts the caller follows, " |
| 352 | "newest-first. A thin wrapper over GET /api/feed -- the caller's own " |
| 353 | "credentials are forwarded, so this can never surface a followed " |
| 354 | "account's private content, only what a direct read of that account " |
| 355 | "would already show the caller. Empty for an anonymous caller or " |
| 356 | "when the caller follows no one." |
| 357 | ), |
| 358 | "inputSchema": { |
| 359 | "type": "object", |
| 360 | "properties": { |
| 361 | "limit": {"type": "integer", "description": "Max items (default 50)", "default": 50}, |
| 362 | "offset": {"type": "integer", "description": "Pagination offset", "default": 0}, |
| 363 | }, |
| 364 | }, |
| 365 | }, |
| 366 | { |
| 367 | "name": "get_stock_levels", |
| 368 | "description": ( |
| 369 | "The caller's on-hand stock, folded from stock_moves: per-(product, " |
| 370 | "location) net quantity and per-product on-hand totals. A derived " |
| 371 | "read (not a plain collection scan) -- thin wrapper over GET /api/" |
| 372 | "stock, owner-scoped. Empty when there are no stock moves." |
| 373 | ), |
| 374 | "inputSchema": {"type": "object", "properties": {}}, |
| 375 | }, |
| 376 | { |
| 377 | "name": "get_finance_summary", |
| 378 | "description": ( |
| 379 | "The caller's trial balance: per-account debit/credit totals over " |
| 380 | "POSTED journals only (draft journals never contribute). A derived " |
| 381 | "read (a fold over journal postings, not a plain collection scan) -- " |
| 382 | "thin wrapper over GET /api/finance/summary, owner-scoped." |
| 383 | ), |
| 384 | "inputSchema": {"type": "object", "properties": {}}, |
| 385 | }, |
| 386 | { |
| 387 | "name": "read_page", |
| 388 | "description": ( |
| 389 | "Fetch a URL server-side and return it stripped to readable text: " |
| 390 | "{title, text, links: [{n, label, href}], final_url, truncated}. " |
| 391 | "Links are numbered in document order so they work as speakable " |
| 392 | "navigation targets. Gated by DBBASIC_ENABLE_READER; refuses " |
| 393 | "non-http(s) schemes and requests aimed at private/internal " |
| 394 | "addresses (SSRF gate)." |
| 395 | ), |
| 396 | "inputSchema": { |
| 397 | "type": "object", |
| 398 | "properties": {"url": {"type": "string", "description": "http(s) URL to fetch"}}, |
| 399 | "required": ["url"], |
| 400 | }, |
| 401 | }, |
| 402 | ] |
| 403 | |
| 404 | TOOL_NAMES = frozenset(tool["name"] for tool in TOOLS) |
| 405 | |
| 406 | |
| 407 | def jsonrpc_response(result: Any, request_id: Any) -> dict[str, Any]: |
| 408 | return {"jsonrpc": "2.0", "id": request_id, "result": result} |
| 409 | |
| 410 | |
| 411 | def jsonrpc_error(code: int, message: str, request_id: Any = None) -> dict[str, Any]: |
| 412 | return { |
| 413 | "jsonrpc": "2.0", |
| 414 | "id": request_id, |
| 415 | "error": {"code": code, "message": message}, |
| 416 | } |
| 417 | |
| 418 | |
| 419 | def handle_initialize(params: Mapping[str, Any]) -> dict[str, Any]: |
| 420 | client_version = params.get("protocolVersion") |
| 421 | negotiated = ( |
| 422 | client_version |
| 423 | if client_version in SUPPORTED_MCP_PROTOCOL_VERSIONS |
| 424 | else MCP_PROTOCOL_VERSION |
| 425 | ) |
| 426 | return { |
| 427 | "protocolVersion": negotiated, |
| 428 | "capabilities": {"tools": {}}, |
| 429 | "serverInfo": dict(SERVER_INFO), |
| 430 | } |
| 431 | |
| 432 | |
| 433 | def handle_tools_list() -> dict[str, Any]: |
| 434 | return {"tools": TOOLS} |
| 435 | |
| 436 | |
| 437 | def tool_route(name: str, arguments: Mapping[str, Any]) -> tuple[str, str, str, bytes]: |
| 438 | """Map one tool call to (method, path, query_string, body) on the admin surface.""" |
| 439 | if name not in TOOL_NAMES: |
| 440 | raise ValueError(f"Unknown tool: {name}") |
| 441 | |
| 442 | args = dict(arguments or {}) |
| 443 | |
| 444 | if name == "get_admin_status": |
| 445 | return ("GET", "/admin/status", "", b"") |
| 446 | if name == "list_objects": |
| 447 | return ("GET", "/admin/objects", "", b"") |
| 448 | if name == "get_object_source": |
| 449 | return ("GET", _object_path(args), "source=true&format=json", b"") |
| 450 | if name == "get_object_state": |
| 451 | return ("GET", _object_path(args), "state=true", b"") |
| 452 | if name == "get_object_logs": |
| 453 | return ("GET", _object_path(args), f"logs=true&limit={_limit(args)}", b"") |
| 454 | if name == "get_object_metadata": |
| 455 | return ("GET", _object_path(args), "metadata=true", b"") |
| 456 | if name == "get_object_changes": |
| 457 | return ("GET", _object_path(args), f"changes=true&limit={_limit(args)}", b"") |
| 458 | if name == "create_object": |
| 459 | body = { |
| 460 | "object_id": _required_str(args, "object_id"), |
| 461 | "code": _required_str(args, "code"), |
| 462 | "message": args.get("message") or "Created via MCP", |
| 463 | "author": "mcp", |
| 464 | } |
| 465 | return ("POST", "/admin/objects", "", _json_bytes(body)) |
| 466 | if name == "update_object_source": |
| 467 | body = { |
| 468 | "code": _required_str(args, "code"), |
| 469 | "message": args.get("message") or "Updated via MCP", |
| 470 | "author": "mcp", |
| 471 | } |
| 472 | return ("PUT", _object_path(args), "source=true", _json_bytes(body)) |
| 473 | if name == "execute_object": |
| 474 | body = { |
| 475 | "method": args.get("method") or "GET", |
| 476 | "payload": args.get("payload") or {}, |
| 477 | } |
| 478 | return ("POST", f"{_object_path(args)}/execute", "", _json_bytes(body)) |
| 479 | if name == "list_collections": |
| 480 | return ("GET", "/admin/collections", "", b"") |
| 481 | if name == "list_records": |
| 482 | pairs = [("limit", str(_limit(args))), ("offset", str(_offset(args)))] |
| 483 | where = args.get("where") |
| 484 | if where is not None: |
| 485 | pairs.extend(_where_query_pairs(where)) |
| 486 | query = urllib.parse.urlencode(pairs) |
| 487 | return ("GET", f"{_collection_path(args)}/records", query, b"") |
| 488 | if name == "get_record": |
| 489 | return ("GET", _record_path(args), "", b"") |
| 490 | if name == "create_record": |
| 491 | record = args.get("record") |
| 492 | if not isinstance(record, dict): |
| 493 | raise ValueError("record must be an object") |
| 494 | return ("POST", f"{_collection_path(args)}/records", "", _json_bytes(record)) |
| 495 | if name == "update_record": |
| 496 | changes = args.get("changes") |
| 497 | if not isinstance(changes, dict): |
| 498 | raise ValueError("changes must be an object") |
| 499 | # 63: the MCP->HTTP bridge has no header channel, so the precondition |
| 500 | # rides a reserved `expected_rev` body key the PUT handler strips |
| 501 | # before treating the rest as field changes. |
| 502 | expected_rev = args.get("expected_rev") |
| 503 | if expected_rev is not None: |
| 504 | if not isinstance(expected_rev, str): |
| 505 | raise ValueError("expected_rev must be a string") |
| 506 | changes = {**changes, "expected_rev": expected_rev} |
| 507 | return ("PUT", _record_path(args), "", _json_bytes(changes)) |
| 508 | if name == "delete_record": |
| 509 | return ("DELETE", _record_path(args), "", b"") |
| 510 | if name == "get_schema": |
| 511 | return ("GET", _schema_path(args), "format=json", b"") |
| 512 | if name == "update_schema": |
| 513 | schema = args.get("schema") |
| 514 | if not isinstance(schema, dict): |
| 515 | raise ValueError("schema must be an object") |
| 516 | body = { |
| 517 | "schema": schema, |
| 518 | "author": "mcp", |
| 519 | "message": args.get("message") or "Updated schema via MCP", |
| 520 | } |
| 521 | return ("PUT", _schema_path(args), "", _json_bytes(body)) |
| 522 | if name == "rollback_schema": |
| 523 | version_id = args.get("version_id") |
| 524 | if isinstance(version_id, bool) or not isinstance(version_id, int): |
| 525 | raise ValueError("version_id must be an integer") |
| 526 | body = {"action": "rollback", "version_id": version_id} |
| 527 | return ("POST", _schema_path(args), "", _json_bytes(body)) |
| 528 | if name == "global_search": |
| 529 | search_limit = _bounded_int(args.get("limit"), default=10, minimum=1, maximum=100, name="limit") |
| 530 | pairs = [("q", _required_str(args, "query")), ("limit", str(search_limit))] |
| 531 | collections = args.get("collections") |
| 532 | if collections is not None: |
| 533 | if not isinstance(collections, list) or not all( |
| 534 | isinstance(item, str) and item.strip() for item in collections |
| 535 | ): |
| 536 | raise ValueError("collections must be a list of collection names") |
| 537 | pairs.append(("collections", ",".join(item.strip() for item in collections))) |
| 538 | return ("GET", "/api/search", urllib.parse.urlencode(pairs), b"") |
| 539 | if name == "list_ops_events": |
| 540 | pairs = [("limit", str(_limit(args)))] |
| 541 | for key in ("kind", "event"): |
| 542 | value = args.get(key) |
| 543 | if value is not None: |
| 544 | if not isinstance(value, str) or not value.strip(): |
| 545 | raise ValueError(f"{key} must be a non-empty string") |
| 546 | pairs.append((key, value.strip())) |
| 547 | return ("GET", "/admin/ops", urllib.parse.urlencode(pairs), b"") |
| 548 | if name == "list_changes": |
| 549 | pairs = [("limit", str(_limit(args)))] |
| 550 | for key in ("kind", "object_id", "collection"): |
| 551 | value = args.get(key) |
| 552 | if value is not None: |
| 553 | if not isinstance(value, str) or not value.strip(): |
| 554 | raise ValueError(f"{key} must be a non-empty string") |
| 555 | pairs.append((key, value.strip())) |
| 556 | return ("GET", "/admin/changes", urllib.parse.urlencode(pairs), b"") |
| 557 | if name == "get_feed": |
| 558 | # 64 (feed): thin wrapper over the same composed read GET /api/feed |
| 559 | # serves, no separate logic -- mirrors list_records' limit/offset |
| 560 | # handling above. |
| 561 | pairs = [ |
| 562 | ("limit", str(_bounded_int(args.get("limit"), default=50, minimum=1, maximum=200, name="limit"))), |
| 563 | ("offset", str(_bounded_int(args.get("offset"), default=0, minimum=0, maximum=1_000_000, name="offset"))), |
| 564 | ] |
| 565 | return ("GET", "/api/feed", urllib.parse.urlencode(pairs), b"") |
| 566 | if name == "get_stock_levels": |
| 567 | return ("GET", "/api/stock", "", b"") |
| 568 | if name == "get_finance_summary": |
| 569 | return ("GET", "/api/finance/summary", "", b"") |
| 570 | if name == "read_page": |
| 571 | body = {"url": _required_str(args, "url")} |
| 572 | return ("POST", "/api/read", "", _json_bytes(body)) |
| 573 | if name == "start_timer": |
| 574 | payload: dict[str, Any] = {"action": "start"} |
| 575 | for key in ("task_id", "notes"): |
| 576 | payload.update(_optional_payload_str(args, key)) |
| 577 | body = {"method": "POST", "payload": payload} |
| 578 | return ("POST", _timer_actions_execute_path(), "", _json_bytes(body)) |
| 579 | if name == "stop_timer": |
| 580 | payload = {"action": "stop"} |
| 581 | payload.update(_optional_payload_str(args, "time_log_id")) |
| 582 | body = {"method": "POST", "payload": payload} |
| 583 | return ("POST", _timer_actions_execute_path(), "", _json_bytes(body)) |
| 584 | if name == "get_running_timer": |
| 585 | body = {"method": "GET", "payload": {"action": "running"}} |
| 586 | return ("POST", _timer_actions_execute_path(), "", _json_bytes(body)) |
| 587 | if name == "setup_finance_accounts": |
| 588 | # Thin verb over site_setup_accounts (65 slice 4), via the same |
| 589 | # execute bridge start_timer/get_feed use -- no separate logic. |
| 590 | body = {"method": "POST", "payload": {"entity_id": _required_str(args, "entity_id")}} |
| 591 | return ("POST", "/admin/objects/site_setup_accounts/execute", "", _json_bytes(body)) |
| 592 | |
| 593 | raise ValueError(f"Unknown tool: {name}") |
| 594 | |
| 595 | |
| 596 | def _timer_actions_execute_path() -> str: |
| 597 | # 62 (Timer): thin wrappers over site_timer_actions' own routes, via |
| 598 | # the same /admin/objects/{id}/execute bridge the generic |
| 599 | # execute_object tool already uses -- "a thin verb over a primitive |
| 600 | # already built" (plan/vocabulary/62-timer-spec.md's Surfaces |
| 601 | # section), no separate logic. |
| 602 | return "/admin/objects/site_timer_actions/execute" |
| 603 | |
| 604 | |
| 605 | def _optional_payload_str(args: Mapping[str, Any], key: str) -> dict[str, str]: |
| 606 | """Return {key: value} when `args[key]` is a non-empty string, else {}. |
| 607 | |
| 608 | Same optional-string-argument shape list_ops_events/list_changes |
| 609 | already use below: absent is fine (the routed object supplies its |
| 610 | own default), present-but-wrong-typed is a clear client error. |
| 611 | """ |
| 612 | value = args.get(key) |
| 613 | if value is None: |
| 614 | return {} |
| 615 | if not isinstance(value, str) or not value.strip(): |
| 616 | raise ValueError(f"{key} must be a non-empty string") |
| 617 | return {key: value.strip()} |
| 618 | |
| 619 | |
| 620 | def tool_result_content(status: int, payload: Any) -> dict[str, Any]: |
| 621 | """Wrap one internal route response as an MCP tool result.""" |
| 622 | body = {"http_status": status, "response": payload} |
| 623 | return { |
| 624 | "content": [{"type": "text", "text": json.dumps(body, default=str, indent=2)}], |
| 625 | "isError": status >= 400, |
| 626 | } |
| 627 | |
| 628 | |
| 629 | def _json_bytes(payload: Mapping[str, Any]) -> bytes: |
| 630 | return json.dumps(payload).encode("utf-8") |
| 631 | |
| 632 | |
| 633 | def _required_str(args: Mapping[str, Any], key: str) -> str: |
| 634 | value = args.get(key) |
| 635 | if not isinstance(value, str) or not value.strip(): |
| 636 | raise ValueError(f"{key} must be a non-empty string") |
| 637 | return value.strip() |
| 638 | |
| 639 | |
| 640 | def _safe_segment(args: Mapping[str, Any], key: str) -> str: |
| 641 | value = _required_str(args, key) |
| 642 | if "/" in value or "\\" in value or ".." in value or "?" in value or "#" in value: |
| 643 | raise ValueError(f"{key} contains unsafe characters") |
| 644 | return value |
| 645 | |
| 646 | |
| 647 | def _object_path(args: Mapping[str, Any]) -> str: |
| 648 | return f"/admin/objects/{_safe_segment(args, 'object_id')}" |
| 649 | |
| 650 | |
| 651 | def _collection_path(args: Mapping[str, Any]) -> str: |
| 652 | return f"/admin/collections/{_safe_segment(args, 'collection')}" |
| 653 | |
| 654 | |
| 655 | def _record_path(args: Mapping[str, Any]) -> str: |
| 656 | return f"{_collection_path(args)}/records/{_safe_segment(args, 'record_id')}" |
| 657 | |
| 658 | |
| 659 | def _schema_path(args: Mapping[str, Any]) -> str: |
| 660 | return f"/admin/schemas/{_safe_segment(args, 'collection')}" |
| 661 | |
| 662 | |
| 663 | def _limit(args: Mapping[str, Any]) -> int: |
| 664 | return _bounded_int(args.get("limit"), default=100, minimum=1, maximum=1000, name="limit") |
| 665 | |
| 666 | |
| 667 | def _offset(args: Mapping[str, Any]) -> int: |
| 668 | return _bounded_int(args.get("offset"), default=0, minimum=0, maximum=1_000_000, name="offset") |
| 669 | |
| 670 | |
| 671 | def _where_query_pairs(where: Any) -> list[tuple[str, str]]: |
| 672 | """Translate `list_records`' `where` argument into the query params |
| 673 | the collection-records GET route already understands (58's |
| 674 | query-filter language): {field: value} -> field=value (eq); |
| 675 | {field: {"op": op, "value": value}} -> field.op=value; {field: [cond, |
| 676 | cond, ...]} -> one query param per condition, so a range |
| 677 | (`created_at.gte=X&created_at.lte=Y`) round-trips as two params on |
| 678 | the same field rather than one overwriting the other. |
| 679 | |
| 680 | Structural validation only (object shape, non-empty strings) -- the |
| 681 | routed HTTP handler is the single place that validates field names, |
| 682 | operators, and value types against the collection's schema and the |
| 683 | caller's permissions, so a bad filter still comes back as the exact |
| 684 | same structured 400 a direct HTTP caller would get. Nothing new runs |
| 685 | underneath, per this module's own doctrine. |
| 686 | """ |
| 687 | if not isinstance(where, dict): |
| 688 | raise ValueError("where must be an object") |
| 689 | |
| 690 | pairs: list[tuple[str, str]] = [] |
| 691 | for field, condition in where.items(): |
| 692 | if not isinstance(field, str) or not field.strip(): |
| 693 | raise ValueError("where field names must be non-empty strings") |
| 694 | field_name = field.strip() |
| 695 | |
| 696 | for op, value in _where_field_conditions(field_name, condition): |
| 697 | param = field_name if op == "eq" else f"{field_name}.{op}" |
| 698 | pairs.append((param, _where_value_to_string(field_name, value))) |
| 699 | return pairs |
| 700 | |
| 701 | |
| 702 | def _where_field_conditions(field: str, condition: Any) -> list[tuple[str, Any]]: |
| 703 | """Split one `where[field]` value into its (op, value) conditions. |
| 704 | |
| 705 | A list of condition-shaped dicts is multiple ANDed conditions on the |
| 706 | same field, mirroring object_records/object_permissions' own |
| 707 | normalized-filter shape. Anything else is a single condition: a bare |
| 708 | value is an implicit `eq`; one {"op": ..., "value": ...} dict is that |
| 709 | operator (whose value may itself be a list, for `in`). A dict is |
| 710 | never a valid bare filter VALUE (only str/int/float/bool/a list of |
| 711 | those are), so any dict encountered here is always treated as an |
| 712 | attempted condition object, not a literal -- which is what lets a |
| 713 | condition missing "op" raise a clear, on-topic error instead of |
| 714 | falling through to a confusing "not a valid value" one. |
| 715 | """ |
| 716 | if isinstance(condition, list) and condition and all( |
| 717 | isinstance(item, dict) for item in condition |
| 718 | ): |
| 719 | return [_where_condition_op_value(field, item) for item in condition] |
| 720 | return [_where_condition_op_value(field, condition)] |
| 721 | |
| 722 | |
| 723 | def _where_condition_op_value(field: str, condition: Any) -> tuple[str, Any]: |
| 724 | if isinstance(condition, dict): |
| 725 | op = condition.get("op") |
| 726 | if not isinstance(op, str) or not op.strip(): |
| 727 | raise ValueError(f"where.{field}.op must be a non-empty string") |
| 728 | return op.strip().lower(), condition.get("value") |
| 729 | return "eq", condition |
| 730 | |
| 731 | |
| 732 | def _where_value_to_string(field: str, value: Any) -> str: |
| 733 | if isinstance(value, (list, tuple)): |
| 734 | return ",".join(_where_scalar_to_string(field, item) for item in value) |
| 735 | return _where_scalar_to_string(field, value) |
| 736 | |
| 737 | |
| 738 | def _where_scalar_to_string(field: str, value: Any) -> str: |
| 739 | if isinstance(value, bool): |
| 740 | return "true" if value else "false" |
| 741 | if isinstance(value, (str, int, float)): |
| 742 | return str(value) |
| 743 | raise ValueError(f"where.{field} value must be a string, number, boolean, or a list of those") |
| 744 | |
| 745 | |
| 746 | def _bounded_int(value: Any, *, default: int, minimum: int, maximum: int, name: str) -> int: |
| 747 | if value is None: |
| 748 | return default |
| 749 | if isinstance(value, bool) or not isinstance(value, int): |
| 750 | raise ValueError(f"{name} must be an integer") |
| 751 | if value < minimum or value > maximum: |
| 752 | raise ValueError(f"{name} must be between {minimum} and {maximum}") |
| 753 | return value |