elci 0.1.0__tar.gz
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.
- elci-0.1.0/.gitignore +6 -0
- elci-0.1.0/PKG-INFO +95 -0
- elci-0.1.0/README.md +61 -0
- elci-0.1.0/pyproject.toml +48 -0
- elci-0.1.0/src/elci/__init__.py +42 -0
- elci-0.1.0/src/elci/_schemas.py +15 -0
- elci-0.1.0/src/elci/agent.py +39 -0
- elci-0.1.0/src/elci/card.py +76 -0
- elci-0.1.0/src/elci/crypto.py +198 -0
- elci-0.1.0/src/elci/disclosure.py +43 -0
- elci-0.1.0/src/elci/fallback.py +87 -0
- elci-0.1.0/src/elci/inbox.py +254 -0
- elci-0.1.0/src/elci/mcp_server.py +137 -0
- elci-0.1.0/src/elci/schemas/agent-card.schema.json +125 -0
- elci-0.1.0/src/elci/schemas/message.schema.json +21 -0
elci-0.1.0/.gitignore
ADDED
elci-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: elci
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Reference implementation of Elçi, an open person-to-person agent protocol.
|
|
5
|
+
Project-URL: Homepage, https://github.com/ArdaYMC/elci
|
|
6
|
+
Project-URL: Specification, https://github.com/ArdaYMC/elci/tree/main/spec
|
|
7
|
+
Project-URL: Issues, https://github.com/ArdaYMC/elci/issues
|
|
8
|
+
Project-URL: Security, https://github.com/ArdaYMC/elci/security/policy
|
|
9
|
+
Author: Arda Yemci
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
Keywords: a2a,agent-protocol,ai-agents,ed25519,mcp,personal-ai,privacy
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Communications
|
|
23
|
+
Classifier: Topic :: Security :: Cryptography
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
25
|
+
Requires-Python: >=3.10
|
|
26
|
+
Requires-Dist: cryptography>=42
|
|
27
|
+
Requires-Dist: jsonschema>=4.18
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: mcp>=2; extra == 'dev'
|
|
30
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
31
|
+
Provides-Extra: mcp
|
|
32
|
+
Requires-Dist: mcp>=2; extra == 'mcp'
|
|
33
|
+
Description-Content-Type: text/markdown
|
|
34
|
+
|
|
35
|
+
<p align="center">
|
|
36
|
+
<img src="https://raw.githubusercontent.com/ArdaYMC/elci/main/docs/assets/banner.svg" alt="Elçi: your agent talks to their agent, safely" width="100%">
|
|
37
|
+
</p>
|
|
38
|
+
|
|
39
|
+
# elci
|
|
40
|
+
|
|
41
|
+
Reference implementation of [Elçi](https://github.com/ArdaYMC/elci), an open protocol for personal
|
|
42
|
+
AI agents to talk to other people's agents, safely: signed messages, delegated mandates,
|
|
43
|
+
need-to-know disclosure, verifiable human approval, and an email fallback for people without an agent.
|
|
44
|
+
|
|
45
|
+
> Alpha. The spec is a working draft and the API may change between minor versions.
|
|
46
|
+
|
|
47
|
+
## Install
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install elci # library
|
|
51
|
+
pip install 'elci[mcp]' # plus the elci-mcp server for Claude Code and other MCP hosts
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Quick look
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
import time
|
|
58
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
|
59
|
+
from elci import Agent, Delegation, issue_delegation
|
|
60
|
+
|
|
61
|
+
principal_key, agent_key = Ed25519PrivateKey.generate(), Ed25519PrivateKey.generate()
|
|
62
|
+
agent_id = "https://arda.example/agents/devbyarda"
|
|
63
|
+
token = issue_delegation(
|
|
64
|
+
Delegation("arda.example", agent_id, ("collaboration",), ("propose", "answer"), int(time.time()) + 3600),
|
|
65
|
+
principal_key,
|
|
66
|
+
)
|
|
67
|
+
agent = Agent(agent_id, "arda.example", agent_key, token)
|
|
68
|
+
message = agent.message(to="https://brand.example/agents/partnerships", topic="collaboration",
|
|
69
|
+
intent="propose", body={"slots": ["2026-11-27T11:00"]})
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The receiving side runs `elci.Inbox(own_card).accept(message)`, which checks the sender's card,
|
|
73
|
+
domain, freshness, signature, delegation, approval receipt and replays.
|
|
74
|
+
|
|
75
|
+
## Use it from Claude Code
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
pip install 'elci[mcp]'
|
|
79
|
+
claude mcp add elci -- elci-mcp
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Links
|
|
83
|
+
|
|
84
|
+
- [Specification](https://github.com/ArdaYMC/elci/tree/main/spec)
|
|
85
|
+
- [Three-agent demo](https://github.com/ArdaYMC/elci/tree/main/examples)
|
|
86
|
+
- [Security policy](https://github.com/ArdaYMC/elci/security/policy)
|
|
87
|
+
- [Contributing](https://github.com/ArdaYMC/elci/blob/main/CONTRIBUTING.md)
|
|
88
|
+
|
|
89
|
+
## Develop
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
git clone https://github.com/ArdaYMC/elci && cd elci/python
|
|
93
|
+
pip install -e '.[dev]'
|
|
94
|
+
pytest
|
|
95
|
+
```
|
elci-0.1.0/README.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/ArdaYMC/elci/main/docs/assets/banner.svg" alt="Elçi: your agent talks to their agent, safely" width="100%">
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
# elci
|
|
6
|
+
|
|
7
|
+
Reference implementation of [Elçi](https://github.com/ArdaYMC/elci), an open protocol for personal
|
|
8
|
+
AI agents to talk to other people's agents, safely: signed messages, delegated mandates,
|
|
9
|
+
need-to-know disclosure, verifiable human approval, and an email fallback for people without an agent.
|
|
10
|
+
|
|
11
|
+
> Alpha. The spec is a working draft and the API may change between minor versions.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install elci # library
|
|
17
|
+
pip install 'elci[mcp]' # plus the elci-mcp server for Claude Code and other MCP hosts
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Quick look
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
import time
|
|
24
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
|
25
|
+
from elci import Agent, Delegation, issue_delegation
|
|
26
|
+
|
|
27
|
+
principal_key, agent_key = Ed25519PrivateKey.generate(), Ed25519PrivateKey.generate()
|
|
28
|
+
agent_id = "https://arda.example/agents/devbyarda"
|
|
29
|
+
token = issue_delegation(
|
|
30
|
+
Delegation("arda.example", agent_id, ("collaboration",), ("propose", "answer"), int(time.time()) + 3600),
|
|
31
|
+
principal_key,
|
|
32
|
+
)
|
|
33
|
+
agent = Agent(agent_id, "arda.example", agent_key, token)
|
|
34
|
+
message = agent.message(to="https://brand.example/agents/partnerships", topic="collaboration",
|
|
35
|
+
intent="propose", body={"slots": ["2026-11-27T11:00"]})
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The receiving side runs `elci.Inbox(own_card).accept(message)`, which checks the sender's card,
|
|
39
|
+
domain, freshness, signature, delegation, approval receipt and replays.
|
|
40
|
+
|
|
41
|
+
## Use it from Claude Code
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install 'elci[mcp]'
|
|
45
|
+
claude mcp add elci -- elci-mcp
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Links
|
|
49
|
+
|
|
50
|
+
- [Specification](https://github.com/ArdaYMC/elci/tree/main/spec)
|
|
51
|
+
- [Three-agent demo](https://github.com/ArdaYMC/elci/tree/main/examples)
|
|
52
|
+
- [Security policy](https://github.com/ArdaYMC/elci/security/policy)
|
|
53
|
+
- [Contributing](https://github.com/ArdaYMC/elci/blob/main/CONTRIBUTING.md)
|
|
54
|
+
|
|
55
|
+
## Develop
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
git clone https://github.com/ArdaYMC/elci && cd elci/python
|
|
59
|
+
pip install -e '.[dev]'
|
|
60
|
+
pytest
|
|
61
|
+
```
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "elci"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Reference implementation of Elçi, an open person-to-person agent protocol."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
authors = [{ name = "Arda Yemci" }]
|
|
13
|
+
dependencies = ["jsonschema>=4.18", "cryptography>=42"]
|
|
14
|
+
keywords = ["ai-agents", "agent-protocol", "mcp", "a2a", "ed25519", "personal-ai", "privacy"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
22
|
+
"Programming Language :: Python :: 3.10",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Programming Language :: Python :: 3.13",
|
|
26
|
+
"Topic :: Communications",
|
|
27
|
+
"Topic :: Security :: Cryptography",
|
|
28
|
+
"Topic :: Software Development :: Libraries",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
mcp = ["mcp>=2"]
|
|
33
|
+
dev = ["pytest>=8", "mcp>=2"]
|
|
34
|
+
|
|
35
|
+
[project.scripts]
|
|
36
|
+
elci-mcp = "elci.mcp_server:main"
|
|
37
|
+
|
|
38
|
+
[project.urls]
|
|
39
|
+
Homepage = "https://github.com/ArdaYMC/elci"
|
|
40
|
+
Specification = "https://github.com/ArdaYMC/elci/tree/main/spec"
|
|
41
|
+
Issues = "https://github.com/ArdaYMC/elci/issues"
|
|
42
|
+
Security = "https://github.com/ArdaYMC/elci/security/policy"
|
|
43
|
+
|
|
44
|
+
[tool.hatch.build.targets.wheel]
|
|
45
|
+
packages = ["src/elci"]
|
|
46
|
+
|
|
47
|
+
[tool.hatch.build.targets.sdist]
|
|
48
|
+
include = ["src/elci", "README.md", "pyproject.toml"]
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Elçi: an open person-to-person agent protocol (reference implementation)."""
|
|
2
|
+
|
|
3
|
+
from .agent import Agent
|
|
4
|
+
from .card import AgentCard, AgentEntry, CardError, well_known_url
|
|
5
|
+
from .crypto import (
|
|
6
|
+
Delegation,
|
|
7
|
+
SignatureError,
|
|
8
|
+
issue_approval,
|
|
9
|
+
issue_delegation,
|
|
10
|
+
public_jwk,
|
|
11
|
+
sign_message,
|
|
12
|
+
verify_approval,
|
|
13
|
+
verify_delegation,
|
|
14
|
+
verify_message,
|
|
15
|
+
)
|
|
16
|
+
from .disclosure import LEVELS, DisclosurePolicy
|
|
17
|
+
from .fallback import compose_fallback_email, parse_reply
|
|
18
|
+
from .inbox import Inbox, Rejected
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"Agent",
|
|
22
|
+
"Inbox",
|
|
23
|
+
"Rejected",
|
|
24
|
+
"compose_fallback_email",
|
|
25
|
+
"parse_reply",
|
|
26
|
+
"AgentCard",
|
|
27
|
+
"AgentEntry",
|
|
28
|
+
"CardError",
|
|
29
|
+
"Delegation",
|
|
30
|
+
"SignatureError",
|
|
31
|
+
"issue_approval",
|
|
32
|
+
"issue_delegation",
|
|
33
|
+
"public_jwk",
|
|
34
|
+
"sign_message",
|
|
35
|
+
"verify_approval",
|
|
36
|
+
"verify_delegation",
|
|
37
|
+
"verify_message",
|
|
38
|
+
"DisclosurePolicy",
|
|
39
|
+
"LEVELS",
|
|
40
|
+
"well_known_url",
|
|
41
|
+
]
|
|
42
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Load the JSON Schemas bundled with the package.
|
|
2
|
+
|
|
3
|
+
``elci/schemas/`` is a copy of ``spec/schemas/``; ``tests/test_packaging.py`` keeps them identical.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
from functools import lru_cache
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
SCHEMA_DIR = Path(__file__).parent / "schemas"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@lru_cache(maxsize=None)
|
|
14
|
+
def load(name: str) -> dict:
|
|
15
|
+
return json.loads((SCHEMA_DIR / name).read_text(encoding="utf-8"))
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Sending side: an agent that builds signed, delegated Elçi messages."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import secrets
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
|
|
9
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
|
10
|
+
|
|
11
|
+
from .crypto import sign_message
|
|
12
|
+
|
|
13
|
+
PROTOCOL_VERSION = "0.0.2"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Agent:
|
|
18
|
+
id: str # https URL listed in the principal card
|
|
19
|
+
principal_domain: str
|
|
20
|
+
key: Ed25519PrivateKey
|
|
21
|
+
delegation: str # token issued by the principal
|
|
22
|
+
|
|
23
|
+
def message(self, *, to: str, topic: str, intent: str, body: dict, thread: str | None = None,
|
|
24
|
+
created_at: str | None = None, approval: dict | None = None) -> dict:
|
|
25
|
+
msg = {
|
|
26
|
+
"protocol_version": PROTOCOL_VERSION,
|
|
27
|
+
"from": self.id,
|
|
28
|
+
"to": to,
|
|
29
|
+
"on_behalf_of": self.principal_domain,
|
|
30
|
+
"topic": topic,
|
|
31
|
+
"intent": intent,
|
|
32
|
+
"thread": thread or f"thr_{secrets.token_hex(6)}",
|
|
33
|
+
"created_at": created_at or datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
34
|
+
"body": body,
|
|
35
|
+
"delegation": self.delegation,
|
|
36
|
+
}
|
|
37
|
+
if approval is not None:
|
|
38
|
+
msg["approval"] = approval
|
|
39
|
+
return sign_message(msg, self.key)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Agent cards: discovery documents published at /.well-known/elci.json."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from urllib.parse import urlsplit
|
|
7
|
+
|
|
8
|
+
import jsonschema
|
|
9
|
+
|
|
10
|
+
from . import _schemas
|
|
11
|
+
|
|
12
|
+
WELL_KNOWN_PATH = "/.well-known/elci.json"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class CardError(ValueError):
|
|
16
|
+
"""The card does not match the Elçi agent card schema."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def well_known_url(domain_or_url: str) -> str:
|
|
20
|
+
"""Return the card URL for a domain (``example.com``) or any URL on it."""
|
|
21
|
+
raw = domain_or_url if "://" in domain_or_url else f"https://{domain_or_url}"
|
|
22
|
+
parts = urlsplit(raw)
|
|
23
|
+
if parts.scheme != "https" or not parts.hostname:
|
|
24
|
+
raise ValueError(f"agent cards are only served over https: {domain_or_url!r}")
|
|
25
|
+
host = parts.hostname + (f":{parts.port}" if parts.port else "")
|
|
26
|
+
return f"https://{host}{WELL_KNOWN_PATH}"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class AgentEntry:
|
|
31
|
+
id: str
|
|
32
|
+
topics: tuple[str, ...]
|
|
33
|
+
endpoint: str
|
|
34
|
+
keys: tuple[dict, ...] = ()
|
|
35
|
+
jwks_uri: str | None = None
|
|
36
|
+
a2a_card: str | None = None
|
|
37
|
+
name: str | None = None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class AgentCard:
|
|
42
|
+
principal: str
|
|
43
|
+
domain: str
|
|
44
|
+
agents: tuple[AgentEntry, ...]
|
|
45
|
+
fallback: str | None = None
|
|
46
|
+
principal_keys: tuple[dict, ...] = ()
|
|
47
|
+
raw: dict = field(default_factory=dict, compare=False, repr=False)
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def from_dict(cls, data: dict) -> "AgentCard":
|
|
51
|
+
try:
|
|
52
|
+
jsonschema.validate(data, _schemas.load("agent-card.schema.json"))
|
|
53
|
+
except jsonschema.ValidationError as exc:
|
|
54
|
+
raise CardError(exc.message) from exc
|
|
55
|
+
agents = tuple(
|
|
56
|
+
AgentEntry(
|
|
57
|
+
id=a["id"],
|
|
58
|
+
topics=tuple(a["topics"]),
|
|
59
|
+
endpoint=a["endpoint"],
|
|
60
|
+
keys=tuple(a.get("jwks", {}).get("keys", ())),
|
|
61
|
+
jwks_uri=a.get("jwks_uri"),
|
|
62
|
+
a2a_card=a.get("a2a_card"),
|
|
63
|
+
name=a.get("name"),
|
|
64
|
+
)
|
|
65
|
+
for a in data["agents"]
|
|
66
|
+
)
|
|
67
|
+
principal = data["principal"]
|
|
68
|
+
return cls(principal["name"], principal["domain"], agents, principal.get("fallback"),
|
|
69
|
+
tuple(principal.get("jwks", {}).get("keys", ())), data)
|
|
70
|
+
|
|
71
|
+
def agent_for(self, topic: str) -> AgentEntry | None:
|
|
72
|
+
"""First public agent that accepts ``topic``; None means use the fallback."""
|
|
73
|
+
return next((a for a in self.agents if topic in a.topics), None)
|
|
74
|
+
|
|
75
|
+
def agent(self, agent_id: str) -> AgentEntry | None:
|
|
76
|
+
return next((a for a in self.agents if a.id == agent_id), None)
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Signing and delegation for Elçi messages (Ed25519, JWS compact serialization)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
import time
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Iterable
|
|
12
|
+
|
|
13
|
+
from cryptography.exceptions import InvalidSignature
|
|
14
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
|
|
15
|
+
Ed25519PrivateKey,
|
|
16
|
+
Ed25519PublicKey,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SignatureError(ValueError):
|
|
21
|
+
"""A signature or delegation token did not verify."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def b64u(data: bytes) -> str:
|
|
25
|
+
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
_B64U_RE = re.compile(r"[A-Za-z0-9_-]*")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def b64u_decode(text: str) -> bytes:
|
|
32
|
+
"""Strict base64url (no padding) decoding.
|
|
33
|
+
|
|
34
|
+
Rejects padding, characters outside the alphabet and non-zero trailing bits, so every byte
|
|
35
|
+
string has exactly one accepted encoding. Lenient decoders let an attacker re-encode a captured
|
|
36
|
+
signature into endless distinct strings that all verify.
|
|
37
|
+
"""
|
|
38
|
+
if not isinstance(text, str) or not _B64U_RE.fullmatch(text) or len(text) % 4 == 1:
|
|
39
|
+
raise SignatureError("not canonical base64url")
|
|
40
|
+
data = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
|
41
|
+
if b64u(data) != text:
|
|
42
|
+
raise SignatureError("not canonical base64url")
|
|
43
|
+
return data
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def body_digest(obj: object) -> str:
|
|
47
|
+
"""base64url SHA-256 of the canonical JSON of ``obj``; binds approval receipts to a message body."""
|
|
48
|
+
return b64u(hashlib.sha256(canonical(obj)).digest())
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def canonical(obj: object) -> bytes:
|
|
52
|
+
"""Canonical JSON: sorted keys, no whitespace, UTF-8 (a JCS subset without floats)."""
|
|
53
|
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# --- keys -------------------------------------------------------------------
|
|
57
|
+
|
|
58
|
+
def public_jwk(key: Ed25519PublicKey, kid: str | None = None) -> dict:
|
|
59
|
+
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
|
|
60
|
+
|
|
61
|
+
raw = key.public_bytes(Encoding.Raw, PublicFormat.Raw)
|
|
62
|
+
jwk = {"kty": "OKP", "crv": "Ed25519", "x": b64u(raw)}
|
|
63
|
+
if kid:
|
|
64
|
+
jwk["kid"] = kid
|
|
65
|
+
return jwk
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def key_from_jwk(jwk: dict) -> Ed25519PublicKey:
|
|
69
|
+
if jwk.get("kty") != "OKP" or jwk.get("crv") != "Ed25519":
|
|
70
|
+
raise SignatureError("only Ed25519 (kty=OKP, crv=Ed25519) keys are supported")
|
|
71
|
+
return Ed25519PublicKey.from_public_bytes(b64u_decode(jwk["x"]))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _verify_any(keys: Iterable[dict], signature: bytes, data: bytes, kid: str | None) -> None:
|
|
75
|
+
candidates = [k for k in keys if kid is None or k.get("kid") in (None, kid)]
|
|
76
|
+
for jwk in candidates:
|
|
77
|
+
try:
|
|
78
|
+
key_from_jwk(jwk).verify(signature, data)
|
|
79
|
+
return
|
|
80
|
+
except (InvalidSignature, SignatureError):
|
|
81
|
+
continue
|
|
82
|
+
raise SignatureError("no key in the set verifies this signature")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# --- detached message signatures ---------------------------------------------
|
|
86
|
+
|
|
87
|
+
def sign_message(message: dict, key: Ed25519PrivateKey) -> dict:
|
|
88
|
+
"""Return a copy of ``message`` with ``signature`` over its canonical form."""
|
|
89
|
+
body = {k: v for k, v in message.items() if k != "signature"}
|
|
90
|
+
return {**body, "signature": b64u(key.sign(canonical(body)))}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def verify_message(message: dict, keys: Iterable[dict]) -> None:
|
|
94
|
+
"""Raise SignatureError unless some key in ``keys`` signed ``message``."""
|
|
95
|
+
if not isinstance(message.get("signature"), str):
|
|
96
|
+
raise SignatureError("message is not signed")
|
|
97
|
+
body = {k: v for k, v in message.items() if k != "signature"}
|
|
98
|
+
_verify_any(keys, b64u_decode(message["signature"]), canonical(body), None)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# --- delegation tokens (compact JWS, alg EdDSA) -------------------------------
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True)
|
|
104
|
+
class Delegation:
|
|
105
|
+
principal: str # iss: the principal's domain
|
|
106
|
+
agent: str # sub: the agent id URL
|
|
107
|
+
topics: tuple[str, ...]
|
|
108
|
+
intents: tuple[str, ...]
|
|
109
|
+
expires_at: int # exp, unix seconds
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def issue_delegation(d: Delegation, principal_key: Ed25519PrivateKey, kid: str | None = None,
|
|
113
|
+
now: int | None = None) -> str:
|
|
114
|
+
header = {"alg": "EdDSA", "typ": "elci-delegation+jwt"}
|
|
115
|
+
if kid:
|
|
116
|
+
header["kid"] = kid
|
|
117
|
+
claims = {
|
|
118
|
+
"iss": d.principal,
|
|
119
|
+
"sub": d.agent,
|
|
120
|
+
"topics": list(d.topics),
|
|
121
|
+
"intents": list(d.intents),
|
|
122
|
+
"iat": int(time.time()) if now is None else now,
|
|
123
|
+
"exp": d.expires_at,
|
|
124
|
+
}
|
|
125
|
+
signing_input = f"{b64u(canonical(header))}.{b64u(canonical(claims))}"
|
|
126
|
+
return f"{signing_input}.{b64u(principal_key.sign(signing_input.encode('ascii')))}"
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def verify_delegation(token: str, principal_keys: Iterable[dict], *, agent: str, topic: str,
|
|
130
|
+
intent: str, principal: str | None = None, now: int | None = None) -> Delegation:
|
|
131
|
+
"""Verify a delegation token and that it covers ``agent``, ``topic`` and ``intent``.
|
|
132
|
+
|
|
133
|
+
When ``principal`` is given, the token's ``iss`` must name that principal's domain.
|
|
134
|
+
"""
|
|
135
|
+
try:
|
|
136
|
+
h64, c64, s64 = token.split(".")
|
|
137
|
+
header = json.loads(b64u_decode(h64))
|
|
138
|
+
claims = json.loads(b64u_decode(c64))
|
|
139
|
+
except ValueError as exc:
|
|
140
|
+
raise SignatureError("malformed delegation token") from exc
|
|
141
|
+
if not isinstance(header, dict) or not isinstance(claims, dict):
|
|
142
|
+
raise SignatureError("malformed delegation token")
|
|
143
|
+
if header.get("alg") != "EdDSA":
|
|
144
|
+
raise SignatureError("delegation must use alg EdDSA")
|
|
145
|
+
if header.get("typ") != "elci-delegation+jwt":
|
|
146
|
+
raise SignatureError("delegation must have typ elci-delegation+jwt")
|
|
147
|
+
_verify_any(principal_keys, b64u_decode(s64), f"{h64}.{c64}".encode("ascii"), header.get("kid"))
|
|
148
|
+
exp, topics, intents = claims.get("exp"), claims.get("topics"), claims.get("intents")
|
|
149
|
+
if (not isinstance(exp, int) or isinstance(exp, bool) or not isinstance(claims.get("iss"), str)
|
|
150
|
+
or not isinstance(topics, list) or not isinstance(intents, list)):
|
|
151
|
+
raise SignatureError("malformed delegation claims")
|
|
152
|
+
current = int(time.time()) if now is None else now
|
|
153
|
+
if exp <= current:
|
|
154
|
+
raise SignatureError("delegation expired")
|
|
155
|
+
if principal is not None and claims["iss"].lower() != principal.lower():
|
|
156
|
+
raise SignatureError("delegation was issued by a different principal")
|
|
157
|
+
if claims.get("sub") != agent:
|
|
158
|
+
raise SignatureError("delegation was issued to a different agent")
|
|
159
|
+
if topic not in claims.get("topics", []):
|
|
160
|
+
raise SignatureError(f"delegation does not cover topic {topic!r}")
|
|
161
|
+
if intent not in claims.get("intents", []):
|
|
162
|
+
raise SignatureError(f"delegation does not cover intent {intent!r}")
|
|
163
|
+
return Delegation(claims["iss"], claims["sub"], tuple(claims["topics"]),
|
|
164
|
+
tuple(claims["intents"]), claims["exp"])
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
# --- human approval receipts ------------------------------------------------------
|
|
168
|
+
|
|
169
|
+
BINDING_INTENTS = frozenset({"accept"})
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def issue_approval(principal_key: Ed25519PrivateKey, *, principal: str, thread: str, intent: str,
|
|
173
|
+
body: dict, summary: str, now: int | None = None) -> dict:
|
|
174
|
+
"""A receipt, signed by the principal's key, that a human approved one binding step.
|
|
175
|
+
|
|
176
|
+
``body`` is the exact message body the human approved; the receipt only covers that body.
|
|
177
|
+
"""
|
|
178
|
+
receipt = {
|
|
179
|
+
"type": "elci-approval",
|
|
180
|
+
"principal": principal,
|
|
181
|
+
"thread": thread,
|
|
182
|
+
"intent": intent,
|
|
183
|
+
"body_sha256": body_digest(body),
|
|
184
|
+
"summary": summary,
|
|
185
|
+
"approved_at": int(time.time()) if now is None else now,
|
|
186
|
+
}
|
|
187
|
+
return sign_message(receipt, principal_key)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def verify_approval(receipt: dict, principal_keys: Iterable[dict], *, principal: str, thread: str,
|
|
191
|
+
intent: str, body: dict) -> None:
|
|
192
|
+
if not isinstance(receipt, dict) or receipt.get("type") != "elci-approval":
|
|
193
|
+
raise SignatureError("missing or malformed approval receipt")
|
|
194
|
+
verify_message(receipt, principal_keys)
|
|
195
|
+
if (receipt.get("principal"), receipt.get("thread"), receipt.get("intent")) != (principal, thread, intent):
|
|
196
|
+
raise SignatureError("approval receipt is for a different principal, thread or intent")
|
|
197
|
+
if receipt.get("body_sha256") != body_digest(body):
|
|
198
|
+
raise SignatureError("approval receipt does not cover this message body")
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Need-to-know disclosure: reveal only what an agent's mandate allows."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
# Ordered from least to most revealing. Each level lists the keys it adds.
|
|
8
|
+
LEVELS: dict[str, dict[str, tuple[str, ...]]] = {
|
|
9
|
+
"availability": {
|
|
10
|
+
"none": (),
|
|
11
|
+
"busy_free": ("slot", "busy"),
|
|
12
|
+
"title": ("title",),
|
|
13
|
+
"full": ("*",),
|
|
14
|
+
},
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class DisclosurePolicy:
|
|
20
|
+
"""Maps a field family (e.g. ``availability``) to the highest level an agent may reveal."""
|
|
21
|
+
|
|
22
|
+
allowed: dict[str, str] = field(default_factory=dict)
|
|
23
|
+
|
|
24
|
+
def visible_keys(self, family: str) -> set[str] | None:
|
|
25
|
+
"""Keys visible for ``family``; None means every key (``full``)."""
|
|
26
|
+
levels = LEVELS[family]
|
|
27
|
+
level = self.allowed.get(family, "none")
|
|
28
|
+
if level not in levels:
|
|
29
|
+
raise ValueError(f"unknown level {level!r} for {family!r}")
|
|
30
|
+
keys: set[str] = set()
|
|
31
|
+
for name, added in levels.items():
|
|
32
|
+
if "*" in added:
|
|
33
|
+
return None
|
|
34
|
+
keys.update(added)
|
|
35
|
+
if name == level:
|
|
36
|
+
break
|
|
37
|
+
return keys
|
|
38
|
+
|
|
39
|
+
def redact(self, record: dict, family: str = "availability") -> dict:
|
|
40
|
+
keys = self.visible_keys(family)
|
|
41
|
+
if keys is None:
|
|
42
|
+
return dict(record)
|
|
43
|
+
return {k: v for k, v in record.items() if k in keys}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Email fallback: reach a person who has no agent, and read their answer back.
|
|
2
|
+
|
|
3
|
+
Composing is deterministic; parsing a human reply is best effort. Per spec section 6, a parsed
|
|
4
|
+
reply is never binding on its own: ``FallbackReply.needs_confirmation`` is always True.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from email import message_from_bytes, policy
|
|
12
|
+
from email.message import EmailMessage
|
|
13
|
+
|
|
14
|
+
THREAD_HEADER = "X-Elci-Thread"
|
|
15
|
+
_FOOTER_RE = re.compile(r"elci-thread:\s*([A-Za-z0-9_-]{8,})")
|
|
16
|
+
_YES = {"yes", "ok", "okay", "sure", "evet", "tamam", "olur", "uygun"}
|
|
17
|
+
_NO = {"no", "decline", "hayır", "hayir", "olmaz", "uygun değil", "uygun degil"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def compose_fallback_email(message: dict, *, from_addr: str, to_addr: str, sender_name: str) -> EmailMessage:
|
|
21
|
+
"""Turn a ``propose`` or ``query`` Elçi message into a plain email a human can answer."""
|
|
22
|
+
body = message.get("body", {})
|
|
23
|
+
options = body.get("slots") or body.get("options") or []
|
|
24
|
+
lines = [f"Merhaba / Hello,", "", f"{sender_name} sizinle şu konuda iletişime geçmek istiyor / "
|
|
25
|
+
f"would like to reach you about: {message['topic']}."]
|
|
26
|
+
if body.get("note"):
|
|
27
|
+
lines += ["", str(body["note"])]
|
|
28
|
+
if options:
|
|
29
|
+
lines += ["", "Seçenekler / Options:"]
|
|
30
|
+
lines += [f" {i}. {opt}" for i, opt in enumerate(options, start=1)]
|
|
31
|
+
lines += ["", "Uygun olanın numarasıyla cevap verin, ya da \"hayır\" yazın. / "
|
|
32
|
+
"Reply with the number that suits you, or \"no\"."]
|
|
33
|
+
lines += ["", "--", f"Bu e-postayı {sender_name} adına bir asistan gönderdi; cevabınızı {sender_name} onaylayacak.",
|
|
34
|
+
f"Sent by an assistant on behalf of {sender_name}; {sender_name} confirms every answer.",
|
|
35
|
+
f"elci-thread: {message['thread']}"]
|
|
36
|
+
email = EmailMessage()
|
|
37
|
+
email["From"] = from_addr
|
|
38
|
+
email["To"] = to_addr
|
|
39
|
+
email["Subject"] = f"[{sender_name}] {message['topic']}"
|
|
40
|
+
email[THREAD_HEADER] = message["thread"]
|
|
41
|
+
email.set_content("\n".join(lines))
|
|
42
|
+
return email
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class FallbackReply:
|
|
47
|
+
thread: str | None
|
|
48
|
+
choice: int | None # 1-based option number the person picked
|
|
49
|
+
declined: bool
|
|
50
|
+
accepted: bool
|
|
51
|
+
text: str # the person's own words, quoted history removed
|
|
52
|
+
needs_confirmation: bool = True
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _own_words(text: str) -> str:
|
|
56
|
+
kept = []
|
|
57
|
+
for line in text.splitlines():
|
|
58
|
+
stripped = line.strip()
|
|
59
|
+
if stripped.startswith(">"):
|
|
60
|
+
continue
|
|
61
|
+
if re.match(r"^(On .+ wrote:|.+ tarihinde .+ yazdı:)$", stripped):
|
|
62
|
+
break
|
|
63
|
+
if stripped == "--":
|
|
64
|
+
break
|
|
65
|
+
kept.append(line)
|
|
66
|
+
return "\n".join(kept).strip()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def parse_reply(raw: bytes) -> FallbackReply:
|
|
70
|
+
"""Best-effort reading of a human reply to a fallback email."""
|
|
71
|
+
msg = message_from_bytes(raw, policy=policy.default)
|
|
72
|
+
part = msg.get_body(preferencelist=("plain",))
|
|
73
|
+
full = part.get_content() if part else ""
|
|
74
|
+
thread = msg.get(THREAD_HEADER)
|
|
75
|
+
if not thread:
|
|
76
|
+
found = _FOOTER_RE.search(full)
|
|
77
|
+
thread = found.group(1) if found else None
|
|
78
|
+
words = _own_words(full)
|
|
79
|
+
first = words.splitlines()[0].strip().lower() if words else ""
|
|
80
|
+
choice = None
|
|
81
|
+
m = re.match(r"^\(?(\d{1,2})\)?[.,)]?(\s|$)", first)
|
|
82
|
+
if m:
|
|
83
|
+
choice = int(m.group(1))
|
|
84
|
+
cleaned = first.strip(" .!")
|
|
85
|
+
declined = cleaned in _NO or cleaned.startswith(("hayır", "hayir", "no ", "no,"))
|
|
86
|
+
accepted = choice is not None or cleaned in _YES
|
|
87
|
+
return FallbackReply(thread, choice, declined, accepted and not declined, words)
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Receiving side: the checks every incoming Elçi message must pass, plus a tiny HTTP transport."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import ipaddress
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.request
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
15
|
+
from typing import Callable
|
|
16
|
+
from urllib.parse import urlsplit
|
|
17
|
+
|
|
18
|
+
import jsonschema
|
|
19
|
+
|
|
20
|
+
from . import _schemas
|
|
21
|
+
from .card import AgentCard
|
|
22
|
+
from .crypto import (
|
|
23
|
+
BINDING_INTENTS,
|
|
24
|
+
SignatureError,
|
|
25
|
+
canonical,
|
|
26
|
+
verify_approval,
|
|
27
|
+
verify_delegation,
|
|
28
|
+
verify_message,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
CardResolver = Callable[[str], AgentCard] # domain -> card
|
|
32
|
+
KeyFetcher = Callable[[str], list[dict]] # jwks_uri -> keys
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Rejected(ValueError):
|
|
36
|
+
"""The message failed a protocol check. ``status`` is the HTTP code to answer with."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, reason: str, status: int = 400):
|
|
39
|
+
super().__init__(reason)
|
|
40
|
+
self.status = status
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
MAX_DOCUMENT_BYTES = 64 * 1024 # cards and key sets are small; refuse anything bigger
|
|
44
|
+
MAX_MESSAGE_BYTES = 256 * 1024
|
|
45
|
+
# Labels of letters, digits and hyphens; the last label starts with a letter, which also rules out
|
|
46
|
+
# IP literals in every notation (127.0.0.1, 0x7f.1, 2130706433).
|
|
47
|
+
_HOSTNAME_RE = re.compile(r"(?=.{1,253}$)((?!-)[a-z0-9-]{1,63}(?<!-)\.)+[a-z][a-z0-9-]{0,62}(?<!-)")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def is_domain_name(value: str) -> bool:
|
|
51
|
+
"""True for a plain DNS name such as ``arda.example``: no scheme, port, path, user or IP literal."""
|
|
52
|
+
if not isinstance(value, str) or not _HOSTNAME_RE.fullmatch(value.lower()):
|
|
53
|
+
return False
|
|
54
|
+
try:
|
|
55
|
+
ipaddress.ip_address(value)
|
|
56
|
+
except ValueError:
|
|
57
|
+
return True
|
|
58
|
+
return False
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
62
|
+
def redirect_request(self, *args, **kwargs): # noqa: D102 - never follow, a redirect could leave https
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
_opener = urllib.request.build_opener(_NoRedirect)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _fetch_json(url: str) -> object:
|
|
70
|
+
parts = urlsplit(url)
|
|
71
|
+
if parts.scheme != "https" or not parts.hostname or not is_domain_name(parts.hostname):
|
|
72
|
+
raise ValueError("only https URLs on a DNS name are fetched")
|
|
73
|
+
with _opener.open(url, timeout=10) as resp: # noqa: S310 - https checked above
|
|
74
|
+
data = resp.read(MAX_DOCUMENT_BYTES + 1)
|
|
75
|
+
if len(data) > MAX_DOCUMENT_BYTES:
|
|
76
|
+
raise ValueError("document too large")
|
|
77
|
+
return json.loads(data)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def fetch_jwks(uri: str) -> list[dict]:
|
|
81
|
+
keys = _fetch_json(uri)["keys"]
|
|
82
|
+
if not isinstance(keys, list):
|
|
83
|
+
raise ValueError("keys must be a list")
|
|
84
|
+
return keys
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def fetch_card(domain: str) -> AgentCard:
|
|
88
|
+
if not is_domain_name(domain):
|
|
89
|
+
raise ValueError("a principal is named by its DNS domain")
|
|
90
|
+
return AgentCard.from_dict(_fetch_json(f"https://{domain.lower()}/.well-known/elci.json"))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _host_in_domain(url: str, domain: str) -> bool:
|
|
94
|
+
host = (urlsplit(url).hostname or "").lower()
|
|
95
|
+
domain = domain.lower()
|
|
96
|
+
return host == domain or host.endswith("." + domain)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _timestamp(value: str) -> float:
|
|
100
|
+
return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class Inbox:
|
|
104
|
+
"""Verifies messages addressed to one principal's public agents.
|
|
105
|
+
|
|
106
|
+
``max_age`` and ``max_skew`` (seconds) bound how old, or how far in the future, a message's
|
|
107
|
+
``created_at`` may be. The replay cache only has to remember that window.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
def __init__(self, own_card: AgentCard, resolve_card: CardResolver = fetch_card,
|
|
111
|
+
fetch_keys: KeyFetcher = fetch_jwks, now: Callable[[], int] | None = None,
|
|
112
|
+
max_age: int = 300, max_skew: int = 60):
|
|
113
|
+
self.own_card = own_card
|
|
114
|
+
self.resolve_card = resolve_card
|
|
115
|
+
self.fetch_keys = fetch_keys
|
|
116
|
+
self.now = now
|
|
117
|
+
self.max_age = max_age
|
|
118
|
+
self.max_skew = max_skew
|
|
119
|
+
self._seen: dict[str, float] = {} # message digest -> created_at
|
|
120
|
+
self._lock = threading.Lock()
|
|
121
|
+
|
|
122
|
+
def _clock(self) -> float:
|
|
123
|
+
return self.now() if self.now else time.time()
|
|
124
|
+
|
|
125
|
+
def accept(self, message: dict) -> dict:
|
|
126
|
+
try:
|
|
127
|
+
return self._accept(message)
|
|
128
|
+
except Rejected:
|
|
129
|
+
raise
|
|
130
|
+
except SignatureError as exc:
|
|
131
|
+
raise Rejected(str(exc), 401) from exc
|
|
132
|
+
except (ValueError, TypeError, KeyError, AttributeError) as exc:
|
|
133
|
+
raise Rejected("malformed message") from exc
|
|
134
|
+
|
|
135
|
+
def _accept(self, message: dict) -> dict:
|
|
136
|
+
try:
|
|
137
|
+
jsonschema.validate(message, _schemas.load("message.schema.json"))
|
|
138
|
+
except jsonschema.ValidationError as exc:
|
|
139
|
+
raise Rejected(f"invalid message: {exc.message}") from exc
|
|
140
|
+
|
|
141
|
+
principal = message["on_behalf_of"]
|
|
142
|
+
if not is_domain_name(principal):
|
|
143
|
+
raise Rejected("on_behalf_of must be a DNS domain")
|
|
144
|
+
if not _host_in_domain(message["from"], principal):
|
|
145
|
+
raise Rejected("sender agent id is not on its principal's domain", 401)
|
|
146
|
+
current = self._clock()
|
|
147
|
+
created = _timestamp(message["created_at"])
|
|
148
|
+
if created < current - self.max_age or created > current + self.max_skew:
|
|
149
|
+
raise Rejected("message is too old or from the future", 401)
|
|
150
|
+
|
|
151
|
+
recipient = self.own_card.agent(message["to"])
|
|
152
|
+
if recipient is None:
|
|
153
|
+
raise Rejected("no such agent here", 404)
|
|
154
|
+
if message["topic"] not in recipient.topics:
|
|
155
|
+
raise Rejected(f"agent does not accept topic {message['topic']!r}", 403)
|
|
156
|
+
|
|
157
|
+
try:
|
|
158
|
+
sender_card = self.resolve_card(principal)
|
|
159
|
+
except Exception as exc: # network or schema failure; details stay on this side
|
|
160
|
+
raise Rejected("cannot resolve sender card", 401) from exc
|
|
161
|
+
if sender_card.domain.lower() != principal.lower():
|
|
162
|
+
raise Rejected("sender card is for a different domain", 401)
|
|
163
|
+
sender = sender_card.agent(message["from"])
|
|
164
|
+
if sender is None:
|
|
165
|
+
raise Rejected("sender agent is not listed in its principal's card", 401)
|
|
166
|
+
if sender.keys:
|
|
167
|
+
keys = list(sender.keys)
|
|
168
|
+
else:
|
|
169
|
+
try:
|
|
170
|
+
keys = self.fetch_keys(sender.jwks_uri)
|
|
171
|
+
except Exception as exc:
|
|
172
|
+
raise Rejected("cannot fetch sender keys", 401) from exc
|
|
173
|
+
|
|
174
|
+
verify_message(message, keys)
|
|
175
|
+
if "delegation" not in message:
|
|
176
|
+
raise SignatureError("missing delegation token")
|
|
177
|
+
verify_delegation(message["delegation"], sender_card.principal_keys, agent=sender.id,
|
|
178
|
+
topic=message["topic"], intent=message["intent"], principal=principal,
|
|
179
|
+
now=int(current))
|
|
180
|
+
if message["intent"] in BINDING_INTENTS:
|
|
181
|
+
verify_approval(message.get("approval"), sender_card.principal_keys, principal=principal,
|
|
182
|
+
thread=message["thread"], intent=message["intent"], body=message["body"])
|
|
183
|
+
|
|
184
|
+
# Replay key: the signed content itself, so re-encoding the signature cannot dodge it.
|
|
185
|
+
digest = hashlib.sha256(canonical({k: v for k, v in message.items() if k != "signature"})).hexdigest()
|
|
186
|
+
with self._lock:
|
|
187
|
+
horizon = current - self.max_age
|
|
188
|
+
for key in [k for k, t in self._seen.items() if t < horizon]:
|
|
189
|
+
del self._seen[key]
|
|
190
|
+
if digest in self._seen:
|
|
191
|
+
raise Rejected("replayed message", 409)
|
|
192
|
+
self._seen[digest] = created
|
|
193
|
+
return message
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def serve(inbox: Inbox, handle: Callable[[dict], dict | None], host: str = "127.0.0.1",
|
|
197
|
+
port: int = 0) -> ThreadingHTTPServer:
|
|
198
|
+
"""Start a background HTTP server that runs ``inbox.accept`` then ``handle`` on each POST.
|
|
199
|
+
|
|
200
|
+
Production deployments sit behind HTTPS (spec requires https endpoints); this server is for
|
|
201
|
+
local development, tests and demos.
|
|
202
|
+
"""
|
|
203
|
+
|
|
204
|
+
class Handler(BaseHTTPRequestHandler):
|
|
205
|
+
def do_POST(self): # noqa: N802
|
|
206
|
+
try:
|
|
207
|
+
length = int(self.headers.get("Content-Length", ""))
|
|
208
|
+
except ValueError:
|
|
209
|
+
return self._send(411, {"status": "rejected", "reason": "Content-Length required"})
|
|
210
|
+
if not 0 < length <= MAX_MESSAGE_BYTES:
|
|
211
|
+
return self._send(413, {"status": "rejected", "reason": "body too large or empty"})
|
|
212
|
+
try:
|
|
213
|
+
message = json.loads(self.rfile.read(length))
|
|
214
|
+
inbox.accept(message)
|
|
215
|
+
reply = handle(message)
|
|
216
|
+
self._send(202, {"status": "accepted", "reply": reply})
|
|
217
|
+
except Rejected as exc:
|
|
218
|
+
self._send(exc.status, {"status": "rejected", "reason": str(exc)})
|
|
219
|
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
220
|
+
self._send(400, {"status": "rejected", "reason": "body is not JSON"})
|
|
221
|
+
except Exception: # never leak internals to the sender
|
|
222
|
+
self._send(500, {"status": "error", "reason": "internal error"})
|
|
223
|
+
|
|
224
|
+
def _send(self, code: int, payload: dict):
|
|
225
|
+
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
226
|
+
self.send_response(code)
|
|
227
|
+
self.send_header("Content-Type", "application/json")
|
|
228
|
+
self.send_header("Content-Length", str(len(data)))
|
|
229
|
+
self.end_headers()
|
|
230
|
+
self.wfile.write(data)
|
|
231
|
+
|
|
232
|
+
def log_message(self, *args): # keep test output quiet
|
|
233
|
+
pass
|
|
234
|
+
|
|
235
|
+
server = ThreadingHTTPServer((host, port), Handler)
|
|
236
|
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
237
|
+
return server
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def send(message: dict, endpoint: str, *, allow_insecure_localhost: bool = False) -> tuple[int, dict]:
|
|
241
|
+
parts = urlsplit(endpoint)
|
|
242
|
+
local = parts.hostname in {"127.0.0.1", "localhost", "::1"}
|
|
243
|
+
if parts.scheme != "https" and not (allow_insecure_localhost and local):
|
|
244
|
+
raise ValueError("Elçi endpoints must use https")
|
|
245
|
+
req = urllib.request.Request(endpoint, data=json.dumps(message).encode("utf-8"),
|
|
246
|
+
headers={"Content-Type": "application/json"}, method="POST")
|
|
247
|
+
try:
|
|
248
|
+
with _opener.open(req, timeout=10) as resp: # noqa: S310 - scheme checked above
|
|
249
|
+
return resp.status, json.loads(resp.read(MAX_DOCUMENT_BYTES + 1)[:MAX_DOCUMENT_BYTES] or b"{}")
|
|
250
|
+
except urllib.error.HTTPError as err:
|
|
251
|
+
try:
|
|
252
|
+
return err.code, json.loads(err.read(MAX_DOCUMENT_BYTES) or b"{}")
|
|
253
|
+
except ValueError:
|
|
254
|
+
return err.code, {}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""MCP server: lets any MCP host (Claude Code, Claude Desktop, ...) use Elçi.
|
|
2
|
+
|
|
3
|
+
Configure with environment variables:
|
|
4
|
+
|
|
5
|
+
ELCI_AGENT_ID https URL of this agent, as listed in your principal card
|
|
6
|
+
ELCI_PRINCIPAL_DOMAIN your domain (the card lives at https://<domain>/.well-known/elci.json)
|
|
7
|
+
ELCI_AGENT_KEY_HEX 32-byte Ed25519 seed of the agent key, hex (keep it in a secret store)
|
|
8
|
+
ELCI_DELEGATION delegation token your principal key issued to this agent
|
|
9
|
+
|
|
10
|
+
Run: elci-mcp (stdio)
|
|
11
|
+
|
|
12
|
+
Binding intents (``accept``) are refused unless a principal-signed approval receipt is passed in;
|
|
13
|
+
an agent cannot approve on its own.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import os
|
|
19
|
+
from email import policy
|
|
20
|
+
from email.parser import BytesParser
|
|
21
|
+
|
|
22
|
+
from .card import AgentCard
|
|
23
|
+
from .crypto import BINDING_INTENTS
|
|
24
|
+
from .disclosure import DisclosurePolicy
|
|
25
|
+
from .fallback import compose_fallback_email, parse_reply
|
|
26
|
+
from .inbox import fetch_card, send
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _agent():
|
|
30
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
|
31
|
+
|
|
32
|
+
from .agent import Agent
|
|
33
|
+
|
|
34
|
+
missing = [v for v in ("ELCI_AGENT_ID", "ELCI_PRINCIPAL_DOMAIN", "ELCI_AGENT_KEY_HEX", "ELCI_DELEGATION")
|
|
35
|
+
if not os.environ.get(v)]
|
|
36
|
+
if missing:
|
|
37
|
+
raise RuntimeError(f"set {', '.join(missing)} to send messages")
|
|
38
|
+
key = Ed25519PrivateKey.from_private_bytes(bytes.fromhex(os.environ["ELCI_AGENT_KEY_HEX"]))
|
|
39
|
+
return Agent(os.environ["ELCI_AGENT_ID"], os.environ["ELCI_PRINCIPAL_DOMAIN"], key,
|
|
40
|
+
os.environ["ELCI_DELEGATION"])
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# Plain functions, so they are testable without an MCP host.
|
|
44
|
+
|
|
45
|
+
def discover(domain: str, resolve=fetch_card) -> dict:
|
|
46
|
+
card: AgentCard = resolve(domain)
|
|
47
|
+
return {
|
|
48
|
+
"principal": card.principal,
|
|
49
|
+
"domain": card.domain,
|
|
50
|
+
"fallback": card.fallback,
|
|
51
|
+
"agents": [{"id": a.id, "name": a.name, "topics": list(a.topics)} for a in card.agents],
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def route(domain: str, topic: str, resolve=fetch_card) -> dict:
|
|
56
|
+
"""Which agent to contact for ``topic`` at ``domain``, or the email fallback."""
|
|
57
|
+
card = resolve(domain)
|
|
58
|
+
agent = card.agent_for(topic)
|
|
59
|
+
if agent:
|
|
60
|
+
return {"via": "agent", "agent_id": agent.id, "endpoint": agent.endpoint}
|
|
61
|
+
return {"via": "email", "address": (card.fallback or "").removeprefix("mailto:") or None}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def send_message(domain: str, to_agent_id: str, topic: str, intent: str, body: dict,
|
|
65
|
+
thread: str | None = None, approval: dict | None = None, resolve=fetch_card) -> dict:
|
|
66
|
+
if intent in BINDING_INTENTS and approval is None:
|
|
67
|
+
return {"sent": False, "reason": f"{intent!r} needs a principal-signed approval receipt"}
|
|
68
|
+
card = resolve(domain)
|
|
69
|
+
target = card.agent(to_agent_id)
|
|
70
|
+
if target is None:
|
|
71
|
+
return {"sent": False, "reason": "agent not listed in that card"}
|
|
72
|
+
message = _agent().message(to=to_agent_id, topic=topic, intent=intent, body=body, thread=thread,
|
|
73
|
+
approval=approval)
|
|
74
|
+
status, reply = send(message, target.endpoint)
|
|
75
|
+
return {"sent": status == 202, "status": status, "reply": reply, "thread": message["thread"]}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def draft_email(to_address: str, topic: str, sender_name: str, options: list[str] | None = None,
|
|
79
|
+
note: str | None = None, thread: str | None = None) -> dict:
|
|
80
|
+
"""Draft (never send) a fallback email for someone without an agent."""
|
|
81
|
+
import secrets
|
|
82
|
+
|
|
83
|
+
message = {"topic": topic, "thread": thread or f"thr_{secrets.token_hex(6)}",
|
|
84
|
+
"body": {"slots": options or [], **({"note": note} if note else {})}}
|
|
85
|
+
email = compose_fallback_email(message, from_addr="", to_addr=to_address, sender_name=sender_name)
|
|
86
|
+
return {"to": to_address, "subject": email["Subject"], "body": email.get_content(),
|
|
87
|
+
"thread": message["thread"]}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def read_email_reply(raw_email: str) -> dict:
|
|
91
|
+
parsed = parse_reply(raw_email.encode("utf-8"))
|
|
92
|
+
return {"thread": parsed.thread, "choice": parsed.choice, "accepted": parsed.accepted,
|
|
93
|
+
"declined": parsed.declined, "text": parsed.text, "needs_confirmation": parsed.needs_confirmation}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def redact_availability(records: list[dict], level: str = "busy_free") -> list[dict]:
|
|
97
|
+
policy_ = DisclosurePolicy(allowed={"availability": level})
|
|
98
|
+
return [policy_.redact(r) for r in records]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def build_server():
|
|
102
|
+
from mcp.server.mcpserver import MCPServer
|
|
103
|
+
|
|
104
|
+
server = MCPServer(
|
|
105
|
+
name="elci",
|
|
106
|
+
instructions="Talk to other people's agents with Elçi. Discover a person's agents by domain, "
|
|
107
|
+
"share availability only at the allowed level, draft emails for people without "
|
|
108
|
+
"an agent. Never send a binding 'accept' without the human's signed approval.",
|
|
109
|
+
)
|
|
110
|
+
for fn in (discover, route, send_message, draft_email, read_email_reply, redact_availability):
|
|
111
|
+
server.tool()(_without_resolver(fn))
|
|
112
|
+
return server
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _without_resolver(fn):
|
|
116
|
+
"""Hide the test-only ``resolve`` parameter from the tool schema."""
|
|
117
|
+
import functools
|
|
118
|
+
import inspect
|
|
119
|
+
|
|
120
|
+
sig = inspect.signature(fn)
|
|
121
|
+
if "resolve" not in sig.parameters:
|
|
122
|
+
return fn
|
|
123
|
+
|
|
124
|
+
@functools.wraps(fn)
|
|
125
|
+
def wrapper(*args, **kwargs):
|
|
126
|
+
return fn(*args, **kwargs)
|
|
127
|
+
|
|
128
|
+
wrapper.__signature__ = sig.replace(parameters=[p for n, p in sig.parameters.items() if n != "resolve"])
|
|
129
|
+
return wrapper
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def main() -> None:
|
|
133
|
+
build_server().run("stdio")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
if __name__ == "__main__":
|
|
137
|
+
main()
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "https://github.com/ArdaYMC/elci/spec/schemas/agent-card.schema.json",
|
|
4
|
+
"title": "Elçi principal card (/.well-known/elci.json)",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"required": [
|
|
7
|
+
"protocol_version",
|
|
8
|
+
"principal",
|
|
9
|
+
"agents"
|
|
10
|
+
],
|
|
11
|
+
"properties": {
|
|
12
|
+
"protocol_version": {
|
|
13
|
+
"const": "0.0.2"
|
|
14
|
+
},
|
|
15
|
+
"principal": {
|
|
16
|
+
"type": "object",
|
|
17
|
+
"required": [
|
|
18
|
+
"name",
|
|
19
|
+
"domain"
|
|
20
|
+
],
|
|
21
|
+
"properties": {
|
|
22
|
+
"name": {
|
|
23
|
+
"type": "string",
|
|
24
|
+
"minLength": 1
|
|
25
|
+
},
|
|
26
|
+
"domain": {
|
|
27
|
+
"type": "string",
|
|
28
|
+
"minLength": 1
|
|
29
|
+
},
|
|
30
|
+
"fallback": {
|
|
31
|
+
"type": "string",
|
|
32
|
+
"pattern": "^mailto:"
|
|
33
|
+
},
|
|
34
|
+
"jwks": {
|
|
35
|
+
"type": "object",
|
|
36
|
+
"required": [
|
|
37
|
+
"keys"
|
|
38
|
+
],
|
|
39
|
+
"properties": {
|
|
40
|
+
"keys": {
|
|
41
|
+
"type": "array",
|
|
42
|
+
"minItems": 1,
|
|
43
|
+
"items": {
|
|
44
|
+
"type": "object",
|
|
45
|
+
"required": [
|
|
46
|
+
"kty"
|
|
47
|
+
]
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
"description": "Principal keys that sign delegation tokens (spec section 4)."
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
"agents": {
|
|
56
|
+
"type": "array",
|
|
57
|
+
"items": {
|
|
58
|
+
"type": "object",
|
|
59
|
+
"required": [
|
|
60
|
+
"id",
|
|
61
|
+
"topics",
|
|
62
|
+
"endpoint"
|
|
63
|
+
],
|
|
64
|
+
"oneOf": [
|
|
65
|
+
{
|
|
66
|
+
"required": [
|
|
67
|
+
"jwks"
|
|
68
|
+
]
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
"required": [
|
|
72
|
+
"jwks_uri"
|
|
73
|
+
]
|
|
74
|
+
}
|
|
75
|
+
],
|
|
76
|
+
"properties": {
|
|
77
|
+
"id": {
|
|
78
|
+
"type": "string",
|
|
79
|
+
"pattern": "^https://"
|
|
80
|
+
},
|
|
81
|
+
"name": {
|
|
82
|
+
"type": "string"
|
|
83
|
+
},
|
|
84
|
+
"topics": {
|
|
85
|
+
"type": "array",
|
|
86
|
+
"minItems": 1,
|
|
87
|
+
"items": {
|
|
88
|
+
"type": "string"
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
"endpoint": {
|
|
92
|
+
"type": "string",
|
|
93
|
+
"pattern": "^https://"
|
|
94
|
+
},
|
|
95
|
+
"jwks": {
|
|
96
|
+
"type": "object",
|
|
97
|
+
"required": [
|
|
98
|
+
"keys"
|
|
99
|
+
],
|
|
100
|
+
"properties": {
|
|
101
|
+
"keys": {
|
|
102
|
+
"type": "array",
|
|
103
|
+
"minItems": 1,
|
|
104
|
+
"items": {
|
|
105
|
+
"type": "object",
|
|
106
|
+
"required": [
|
|
107
|
+
"kty"
|
|
108
|
+
]
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
"jwks_uri": {
|
|
114
|
+
"type": "string",
|
|
115
|
+
"pattern": "^https://"
|
|
116
|
+
},
|
|
117
|
+
"a2a_card": {
|
|
118
|
+
"type": "string",
|
|
119
|
+
"pattern": "^https://"
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "https://github.com/ArdaYMC/elci/spec/schemas/message.schema.json",
|
|
4
|
+
"title": "Elçi message envelope",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"required": ["protocol_version", "from", "to", "on_behalf_of", "topic", "intent", "thread", "created_at", "body"],
|
|
7
|
+
"properties": {
|
|
8
|
+
"protocol_version": {"const": "0.0.2"},
|
|
9
|
+
"from": {"type": "string", "pattern": "^https://"},
|
|
10
|
+
"to": {"type": "string"},
|
|
11
|
+
"on_behalf_of": {"type": "string"},
|
|
12
|
+
"topic": {"type": "string"},
|
|
13
|
+
"intent": {"enum": ["propose", "query", "answer", "accept", "decline", "needs_human"]},
|
|
14
|
+
"thread": {"type": "string", "minLength": 8},
|
|
15
|
+
"created_at": {"type": "string", "format": "date-time"},
|
|
16
|
+
"body": {"type": "object"},
|
|
17
|
+
"approval": {"type": "object"},
|
|
18
|
+
"delegation": {"type": "string", "pattern": "^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$"},
|
|
19
|
+
"signature": {"type": "string"}
|
|
20
|
+
}
|
|
21
|
+
}
|