freestream / freestream /mcp_server.py
LoveLogicAI's picture
session.tool MCP passthrough
8d7eb17 verified
Raw History Blame Contribute Delete
5.48 kB
"""Cognition layer bridge — MCP server exposing a live session to any agent.
Transport: stdio JSON-RPC 2.0 (MCP-compatible framing), with the same tool
surface over HTTP when FREESTREAM_MCP_HTTP=host:port is set.
Tools:
session.observe() -> recent utterances / meeting state
session.speak(text) -> TTS + avatar playout (pre-rolled)
session.listen(timeout) -> block for the next final utterance
session.tool(tool, args) -> run a toolbelt call in the session workspace
session.leave() -> end the session
The agent itself (Claude Code, Llama, anything MCP-speaking) is the
participant — FREESTREAM owns presence and persona only.
This scaffold ships the protocol skeleton; session state plumbing lands
with the MVP slice. Run: python -m freestream.mcp_server
"""
from __future__ import annotations
import json
import sys
from typing import Callable
PROTOCOL_VERSION = "2025-06-18"
TOOLS = [
{
"name": "session.observe",
"description": "Return recent meeting events (utterances, participant state).",
"inputSchema": {"type": "object", "properties": {}},
},
{
"name": "session.speak",
"description": "Speak a sentence through the persona pipeline (TTS + avatar).",
"inputSchema": {"type": "object", "properties": {"text": {"type": "string"}},
"required": ["text"]},
},
{
"name": "session.listen",
"description": "Block until the next finalized utterance, return its text.",
"inputSchema": {"type": "object", "properties": {
"timeout_sec": {"type": "number", "default": 30}}},
},
{
"name": "session.tool",
"description": "Run a toolbelt call (shell/read/list/write) in the "
"session workspace; gated by FREESTREAM_TOOLS and "
"audited to the session event chain.",
"inputSchema": {"type": "object",
"properties": {"tool": {"type": "string"},
"args": {"type": "object"}},
"required": ["tool"]},
},
{
"name": "session.leave",
"description": "Leave the meeting and close the session.",
"inputSchema": {"type": "object", "properties": {}},
},
]
def make_dispatch(session) -> Callable[[str, dict], dict]:
"""Bind tool dispatch to a session object. `session` provides
observe(), speak(text), listen(timeout_sec), leave()."""
def dispatch(name: str, args: dict) -> dict:
if name == "session.observe":
return session.observe()
if name == "session.speak":
return session.speak(args["text"])
if name == "session.listen":
return session.listen(args.get("timeout_sec", 30))
if name == "session.tool":
return session.tool_call(args["tool"], args.get("args", {}))
if name == "session.leave":
return session.leave()
raise KeyError(name)
return dispatch
class StubSession:
"""Session stub for wiring tests. MVP slice replaces this with live
ASR/TTS/avatar state backed by the hash-chained event log."""
def __init__(self):
self._events: list[dict] = []
def observe(self) -> dict:
return {"events": self._events[-20:]}
def speak(self, text: str) -> dict:
self._events.append({"type": "agent.speak", "text": text})
return {"accepted": True, "note": "no live session; utterance logged only"}
def listen(self, timeout_sec: float) -> dict:
return {"utterance": None, "timed_out": True}
def tool_call(self, tool: str, args: dict) -> dict:
belt = getattr(self, "toolbelt", None)
if belt is None:
return {"ok": False, "output": "no toolbelt on this session"}
out, ok = belt.run(tool, args)
return {"ok": ok, "output": out}
def leave(self) -> dict:
return {"closed": True}
def serve_stdio(session=None) -> None:
"""Minimal MCP-compatible JSON-RPC 2.0 loop over stdio."""
dispatch = make_dispatch(session or StubSession())
for line in sys.stdin:
line = line.strip()
if not line:
continue
try:
req = json.loads(line)
except ValueError:
continue
resp = {"jsonrpc": "2.0", "id": req.get("id")}
method = req.get("method", "")
if method == "initialize":
resp["result"] = {"protocolVersion": PROTOCOL_VERSION,
"capabilities": {"tools": {}},
"serverInfo": {"name": "freestream", "version": "0.1.0"}}
elif method == "tools/list":
resp["result"] = {"tools": TOOLS}
elif method == "tools/call":
params = req.get("params", {})
try:
result = dispatch(params["name"], params.get("arguments", {}))
resp["result"] = {"content": [{"type": "text",
"text": json.dumps(result)}]}
except KeyError as e:
resp["error"] = {"code": -32602, "message": f"unknown tool {e}"}
elif method.startswith("notifications/"):
continue # notifications get no response
else:
resp["error"] = {"code": -32601, "message": "method not found"}
print(json.dumps(resp), flush=True)
if __name__ == "__main__":
serve_stdio()