tempus-ddb 0.5.3

Local-first B2A security gate with tamper-evident execution receipts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
import asyncio
import json
import os

from dotenv import load_dotenv
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import TextContent, Tool

from ._tempus_ddb import TempusDDB, gen_keys

load_dotenv()

# -- Global configuration ----------------------------------------------
SANDBOX_DIR = os.path.realpath(os.getcwd())
TEMPUS_MODE = os.environ.get("TEMPUS_MODE", "autonomous")
TEMPUS_GATE_KEYFILE = os.environ.get("TEMPUS_GATE_KEYFILE", "keys.json")
TEMPUS_ADMIN_TOOLS = os.environ.get("TEMPUS_ADMIN_TOOLS", "0") == "1"
TEMPUS_LEGACY_TOOLS = os.environ.get("TEMPUS_LEGACY_TOOLS", "0") == "1"
TEMPUS_DESTRUCTIVE_TOOLS = os.environ.get("TEMPUS_DESTRUCTIVE_TOOLS", "0") == "1"
# Development-only compatibility tools that receive private-key file paths from
# the MCP client. Production agents must sign locally and use the signed tools.
TEMPUS_LOCAL_KEYFILE_TOOLS = os.environ.get("TEMPUS_LOCAL_KEYFILE_TOOLS", "0") == "1"

ADMIN_TOOL_NAMES = {
    "tempus_init",
    "tempus_gen_keys",
    "tempus_register_agent",
    "tempus_whoami",
}
LEGACY_TOOL_NAMES = {
    "tempus_record",
    "tempus_record_decision",
    "tempus_validate",
    "tempus_list",
    "tempus_export",
    "tempus_count",
}
DESTRUCTIVE_TOOL_NAMES = {"tempus_cleanup"}
LOCAL_KEYFILE_TOOL_NAMES = {
    "tempus_request_action",
    "tempus_commit_outcome",
}


# -- Path-traversal guard ----------------------------------------------
def validate_path(path: str) -> str:
    """Resolve *path* and ensure it stays inside SANDBOX_DIR."""
    resolved = os.path.realpath(os.path.join(SANDBOX_DIR, path))
    if ".." in os.path.normpath(path).split(os.sep):
        raise ValueError(f"Path contains disallowed '..': {path}")
    if not resolved.startswith(SANDBOX_DIR + os.sep) and resolved != SANDBOX_DIR:
        raise ValueError(f"Path escapes sandbox: {path}")
    return resolved


# -- Input validation helpers -------------------------------------
def validate_json_string(value: str, field_name: str) -> None:
    """Ensure *value* is a valid JSON string."""
    try:
        json.loads(value)
    except (json.JSONDecodeError, TypeError) as exc:
        raise ValueError(f"'{field_name}' must be a valid JSON string: {exc}")


# -- MCP server setup --------------------------------------------------
app = Server("tempus-ddb-mcp")


@app.list_tools()
async def list_tools() -> list[Tool]:
    tools = [
        Tool(
            name="tempus_request_action_signed",
            description="Verify a locally signed intent and issue a signed, single-use permit.",
            inputSchema={
                "type": "object",
                "properties": {
                    "db": {"type": "string", "description": "Tempus database path"},
                    "intent": {
                        "type": "string",
                        "description": "tempus.action-intent.v1 JSON",
                    },
                    "agent_id": {
                        "type": "string",
                        "description": "Ed25519 public key of the requesting agent",
                    },
                    "agent_signature": {
                        "type": "string",
                        "description": "Ed25519 signature over the canonical intent",
                    },
                    "ttl_seconds": {"type": "integer", "minimum": 1, "maximum": 86400},
                },
                "required": ["db", "intent", "agent_id", "agent_signature"],
            },
        ),
        Tool(
            name="tempus_commit_outcome_signed",
            description="Consume an allowed permit with an executor-signed outcome.",
            inputSchema={
                "type": "object",
                "properties": {
                    "db": {"type": "string", "description": "Tempus database path"},
                    "authorization_id": {"type": "string"},
                    "outcome": {
                        "type": "string",
                        "description": "tempus.action-outcome.v1 JSON including executor_id and executor_signature",
                    },
                },
                "required": ["db", "authorization_id", "outcome"],
            },
        ),
        Tool(
            name="tempus_get_trace",
            description="Return the authorization and execution receipts for an action.",
            inputSchema={
                "type": "object",
                "properties": {
                    "db": {"type": "string"},
                    "action_id": {"type": "string"},
                },
                "required": ["db", "action_id"],
            },
        ),
        Tool(
            name="tempus_verify_trace",
            description="Cryptographically verify an action trace end to end.",
            inputSchema={
                "type": "object",
                "properties": {
                    "db": {"type": "string"},
                    "action_id": {"type": "string"},
                },
                "required": ["db", "action_id"],
            },
        ),
        Tool(
            name="tempus_list_agents",
            description="Read the signed registry of agent identities.",
            inputSchema={
                "type": "object",
                "properties": {"db": {"type": "string"}},
                "required": ["db"],
            },
        ),
        Tool(
            name="tempus_list_policies",
            description="Read active and retired signed deterministic policies.",
            inputSchema={
                "type": "object",
                "properties": {"db": {"type": "string"}},
                "required": ["db"],
            },
        ),
        Tool(
            name="tempus_list_identity_events",
            description="Read signed identity rotation and revocation events.",
            inputSchema={
                "type": "object",
                "properties": {"db": {"type": "string"}},
                "required": ["db"],
            },
        ),
    ]
    if TEMPUS_LOCAL_KEYFILE_TOOLS:
        tools.extend(
            [
                Tool(
                    name="tempus_request_action",
                    description="Development-only: sign an intent from a local agent key file and request a permit.",
                    inputSchema={
                        "type": "object",
                        "properties": {
                            "db": {
                                "type": "string",
                                "description": "Tempus database path",
                            },
                            "intent": {
                                "type": "string",
                                "description": "tempus.action-intent.v1 JSON",
                            },
                            "agent_keyfile": {
                                "type": "string",
                                "description": "Requesting agent key file",
                            },
                            "ttl_seconds": {
                                "type": "integer",
                                "minimum": 1,
                                "maximum": 86400,
                            },
                        },
                        "required": ["db", "intent", "agent_keyfile"],
                    },
                ),
                Tool(
                    name="tempus_commit_outcome",
                    description="Development-only: sign an executor outcome from a local key file and append it.",
                    inputSchema={
                        "type": "object",
                        "properties": {
                            "db": {
                                "type": "string",
                                "description": "Tempus database path",
                            },
                            "authorization_id": {"type": "string"},
                            "outcome": {
                                "type": "string",
                                "description": "tempus.action-outcome.v1 JSON",
                            },
                            "executor_keyfile": {
                                "type": "string",
                                "description": "Executor key file",
                            },
                        },
                        "required": [
                            "db",
                            "authorization_id",
                            "outcome",
                            "executor_keyfile",
                        ],
                    },
                ),
            ]
        )
    if TEMPUS_ADMIN_TOOLS:
        tools.extend(
            [
                Tool(
                    name="tempus_init",
                    description="Initialize the SQLite database schema for Tempus DDB.",
                    inputSchema={
                        "type": "object",
                        "properties": {
                            "db": {
                                "type": "string",
                                "description": "Database file path",
                            }
                        },
                        "required": ["db"],
                    },
                ),
                Tool(
                    name="tempus_gen_keys",
                    description="Generate a new Ed25519 cryptographic keypair.",
                    inputSchema={
                        "type": "object",
                        "properties": {
                            "output": {
                                "type": "string",
                                "description": "Key file output path",
                            }
                        },
                        "required": ["output"],
                    },
                ),
                Tool(
                    name="tempus_register_agent",
                    description="Register an agent through a gate-signed immutable delegation event.",
                    inputSchema={
                        "type": "object",
                        "properties": {
                            "db": {
                                "type": "string",
                                "description": "Database file path",
                            },
                            "public_key": {
                                "type": "string",
                                "description": "Ed25519 public key (64 hex chars)",
                            },
                            "alias": {
                                "type": "string",
                                "description": "Human-readable alias for the agent",
                            },
                            "metadata": {
                                "type": "string",
                                "description": "Optional JSON metadata for the agent",
                            },
                        },
                        "required": ["db", "public_key", "alias"],
                    },
                ),
                Tool(
                    name="tempus_whoami",
                    description="Return the identity (public key and alias) of the current agent based on the keyfile.",
                    inputSchema={
                        "type": "object",
                        "properties": {
                            "db": {
                                "type": "string",
                                "description": "Database file path",
                            },
                            "keyfile": {
                                "type": "string",
                                "description": "Path to the agent's key file",
                            },
                        },
                        "required": ["db", "keyfile"],
                    },
                ),
            ]
        )
    if TEMPUS_LEGACY_TOOLS:
        for name, description in [
            ("tempus_record_decision", "Legacy direct decision recorder."),
            ("tempus_record", "Legacy alias for direct decision recording."),
        ]:
            tools.append(
                Tool(
                    name=name,
                    description=description,
                    inputSchema={
                        "type": "object",
                        "properties": {
                            "db": {"type": "string"},
                            "payload": {"type": "string"},
                            "rules": {"type": "string"},
                            "keyfile": {"type": "string"},
                            "genesis": {"type": "boolean"},
                        },
                        "required": ["db", "payload", "rules", "keyfile"],
                    },
                )
            )
        for name, description in [
            ("tempus_validate", "Validate the legacy decision chain."),
            ("tempus_list", "List legacy decisions."),
            ("tempus_export", "Export legacy decisions."),
            ("tempus_count", "Count legacy decisions."),
        ]:
            tools.append(
                Tool(
                    name=name,
                    description=description,
                    inputSchema={
                        "type": "object",
                        "properties": {
                            "db": {"type": "string"},
                            "limit": {"type": "integer"},
                            "offset": {"type": "integer"},
                        },
                        "required": ["db"],
                    },
                )
            )
    if TEMPUS_DESTRUCTIVE_TOOLS:
        tools.append(
            Tool(
                name="tempus_cleanup",
                description="Delete demo database and keys. Disabled by default.",
                inputSchema={"type": "object", "properties": {}, "required": []},
            )
        )
    return tools


def _handle_record(arguments: dict) -> list[TextContent]:
    """Shared implementation for tempus_record and tempus_record_decision."""
    payload = arguments["payload"]
    rules = arguments["rules"]
    validate_json_string(payload, "payload")
    validate_json_string(rules, "rules")

    db = validate_path(arguments["db"])
    keyfile = validate_path(arguments["keyfile"])

    genesis = arguments.get("genesis", False)

    db_instance = TempusDDB(db, keyfile)
    output = db_instance.record(payload, rules, genesis)

    result = {
        "status": "success",
        "message": "Record successful.",
        "output": json.loads(output)
        if isinstance(output, str)
        and (output.strip().startswith("{") or output.strip().startswith("["))
        else output,
    }
    if TEMPUS_MODE == "demo":
        result["mode"] = TEMPUS_MODE
    return [TextContent(type="text", text=json.dumps(result, indent=2))]


def _gate_keyfile() -> str:
    """Return the server-controlled gate key; clients cannot override it."""
    return validate_path(TEMPUS_GATE_KEYFILE)


def _gate_db(arguments: dict) -> TempusDDB:
    db_path = validate_path(arguments.get("db", "tempus.db"))
    return TempusDDB(db_path, _gate_keyfile())


@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
    try:
        if name in ADMIN_TOOL_NAMES and not TEMPUS_ADMIN_TOOLS:
            raise PermissionError("TEMPUS_ADMIN_TOOL_DISABLED")
        if name in LEGACY_TOOL_NAMES and not TEMPUS_LEGACY_TOOLS:
            raise PermissionError("TEMPUS_LEGACY_TOOL_DISABLED")
        if name in DESTRUCTIVE_TOOL_NAMES and not TEMPUS_DESTRUCTIVE_TOOLS:
            raise PermissionError("TEMPUS_DESTRUCTIVE_TOOL_DISABLED")
        if name in LOCAL_KEYFILE_TOOL_NAMES and not TEMPUS_LOCAL_KEYFILE_TOOLS:
            raise PermissionError("TEMPUS_LOCAL_KEYFILE_TOOL_DISABLED")

        if name == "tempus_request_action_signed":
            intent = arguments["intent"]
            validate_json_string(intent, "intent")
            output = _gate_db(arguments).request_action_signed(
                intent,
                arguments["agent_id"],
                arguments["agent_signature"],
                arguments.get("ttl_seconds", 60),
            )
            return [TextContent(type="text", text=output)]

        elif name == "tempus_commit_outcome_signed":
            outcome = arguments["outcome"]
            validate_json_string(outcome, "outcome")
            output = _gate_db(arguments).commit_outcome_signed(
                arguments["authorization_id"],
                outcome,
            )
            return [TextContent(type="text", text=output)]

        elif name == "tempus_request_action":
            intent = arguments["intent"]
            validate_json_string(intent, "intent")
            agent_keyfile = validate_path(arguments["agent_keyfile"])
            output = _gate_db(arguments).request_action(
                intent,
                agent_keyfile,
                arguments.get("ttl_seconds", 60),
            )
            return [TextContent(type="text", text=output)]

        elif name == "tempus_commit_outcome":
            outcome = arguments["outcome"]
            validate_json_string(outcome, "outcome")
            executor_keyfile = validate_path(arguments["executor_keyfile"])
            output = _gate_db(arguments).commit_outcome(
                arguments["authorization_id"],
                outcome,
                executor_keyfile,
            )
            return [TextContent(type="text", text=output)]

        elif name == "tempus_get_trace":
            output = _gate_db(arguments).get_trace(arguments["action_id"])
            return [TextContent(type="text", text=output)]

        elif name == "tempus_verify_trace":
            output = _gate_db(arguments).verify_trace(arguments["action_id"])
            return [TextContent(type="text", text=output)]

        if name == "tempus_init":
            db_path = validate_path(arguments.get("db", "tempus.db"))
            db = TempusDDB(db_path, _gate_keyfile())
            identity = json.loads(db.whoami())
            if not db.verify_agent(identity["public_key"]):
                db.register_agent(
                    identity["public_key"],
                    "tempus-gate",
                    json.dumps({"can_delegate": True, "role": "gate"}),
                )
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "status": "success",
                            "message": f"Database initialized: {db_path}",
                            "db_path": db_path,
                        },
                        indent=2,
                    ),
                )
            ]

        elif name == "tempus_gen_keys":
            output_file = validate_path(arguments.get("output", TEMPUS_GATE_KEYFILE))
            output = gen_keys(output_file)
            try:
                output_json = json.loads(output)
                if isinstance(output_json, dict) and "private_key" in output_json:
                    del output_json["private_key"]
            except Exception:
                output_json = output
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "status": "success",
                            "message": f"Keys generated at {output_file}",
                            "key_file": output_file,
                            "output": output_json,
                        },
                        indent=2,
                    ),
                )
            ]

        elif name in ("tempus_record", "tempus_record_decision"):
            return _handle_record(arguments)

        elif name == "tempus_validate":
            db_path = validate_path(arguments.get("db", "tempus.db"))
            db = TempusDDB(db_path, _gate_keyfile())
            try:
                output = db.validate()
                out_str = str(output).lower()
                if "invalid" in out_str or "mismatch" in out_str or "error" in out_str:
                    raise RuntimeError(f"TEMPUS_LEDGER_INTEGRITY_FAILURE: {output}")
            except Exception as e:
                if "TEMPUS_LEDGER_INTEGRITY_FAILURE" not in str(e):
                    raise RuntimeError(f"TEMPUS_LEDGER_INTEGRITY_FAILURE: {e!s}")
                raise

            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "status": "success",
                            "message": "Validation query completed.",
                            "db_path": db_path,
                            "result": output,
                        },
                        indent=2,
                    ),
                )
            ]

        elif name == "tempus_list":
            db_path = validate_path(arguments.get("db", "tempus.db"))
            limit = arguments.get("limit", 10)
            offset = arguments.get("offset", 0)
            db = TempusDDB(db_path, _gate_keyfile())
            output = db.list(limit=limit, offset=offset)
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "status": "success",
                            "message": f"Listed {limit} decisions (offset {offset}).",
                            "db_path": db_path,
                            "decisions": json.loads(output)
                            if isinstance(output, str)
                            else output,
                        },
                        indent=2,
                    ),
                )
            ]

        elif name == "tempus_export":
            db_path = validate_path(arguments.get("db", "tempus.db"))
            db = TempusDDB(db_path, _gate_keyfile())
            output = db.export()
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "status": "success",
                            "message": "Ledger exported successfully.",
                            "db_path": db_path,
                            "decisions": json.loads(output)
                            if isinstance(output, str)
                            else output,
                        },
                        indent=2,
                    ),
                )
            ]

        elif name == "tempus_count":
            db_path = validate_path(arguments.get("db", "tempus.db"))
            db = TempusDDB(db_path, _gate_keyfile())
            count = db.count()
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "status": "success",
                            "message": f"Total decisions: {count}",
                            "db_path": db_path,
                            "total_decisions": count,
                        },
                        indent=2,
                    ),
                )
            ]

        elif name == "tempus_cleanup":
            db_path = os.path.join(SANDBOX_DIR, "tempus.db")
            keys_path = os.path.join(SANDBOX_DIR, "keys.json")
            removed = []
            for p in [db_path, keys_path]:
                if os.path.exists(p):
                    os.remove(p)
                    removed.append(p)
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "status": "success",
                            "message": "Cleanup successful.",
                            "removed": removed,
                        },
                        indent=2,
                    ),
                )
            ]

        elif name == "tempus_register_agent":
            db_path = validate_path(arguments.get("db", "tempus.db"))
            public_key = arguments["public_key"]
            alias = arguments["alias"]
            metadata = arguments.get("metadata", "{}")
            db = TempusDDB(db_path, _gate_keyfile())
            output = db.register_agent(public_key, alias, metadata)
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "status": "success",
                            "message": f"Agent '{alias}' registered.",
                            "db_path": db_path,
                            "result": json.loads(output)
                            if isinstance(output, str)
                            else output,
                        },
                        indent=2,
                    ),
                )
            ]

        elif name == "tempus_list_agents":
            db_path = validate_path(arguments.get("db", "tempus.db"))
            db = TempusDDB(db_path, _gate_keyfile())
            output = db.list_agents()
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "status": "success",
                            "message": "Agents listed.",
                            "db_path": db_path,
                            "agents": json.loads(output)
                            if isinstance(output, str)
                            else output,
                        },
                        indent=2,
                    ),
                )
            ]

        elif name == "tempus_list_policies":
            output = _gate_db(arguments).list_policies()
            return [TextContent(type="text", text=output)]

        elif name == "tempus_list_identity_events":
            output = _gate_db(arguments).list_identity_events()
            return [TextContent(type="text", text=output)]

        elif name == "tempus_whoami":
            db_path = validate_path(arguments.get("db", "tempus.db"))
            keyfile = validate_path(arguments.get("keyfile", "keys.json"))
            db = TempusDDB(db_path, keyfile)
            output = db.whoami()
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "status": "success",
                            "message": "Agent identity retrieved.",
                            "identity": json.loads(output)
                            if isinstance(output, str)
                            else output,
                        },
                        indent=2,
                    ),
                )
            ]

        else:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "status": "error",
                            "error": "TEMPUS_UNKNOWN_TOOL",
                            "message": f"Unknown tool: {name}",
                        },
                        indent=2,
                    ),
                )
            ]

    except Exception as e:
        err_msg = str(e)
        error_code = "TEMPUS_EXECUTION_ERROR"
        for token in err_msg.replace(":", " ").split():
            if token.startswith("TEMPUS_"):
                error_code = token
                break

        return [
            TextContent(
                type="text",
                text=json.dumps(
                    {
                        "status": "error",
                        "error": error_code,
                        "tool": name,
                        "message": err_msg,
                    },
                    indent=2,
                ),
            )
        ]


async def main():
    try:
        async with stdio_server() as (read_stream, write_stream):
            await app.run(
                read_stream, write_stream, app.create_initialization_options()
            )
    except KeyboardInterrupt:
        pass


def main_sync():
    """Entry point for the tempus-mcp console script."""
    asyncio.run(main())


if __name__ == "__main__":
    main_sync()