Spaces:
Sleeping
Sleeping
Download debatemind/server.py from Smzu890/DebateMind: direct link, hf CLI and curl.
- Browser
- Download file 7.25 kB
-
https://huggingface.co/spaces/Smzu890/DebateMind/resolve/main/debatemind/server.py
- Command line
-
hf download hf://spaces/Smzu890/DebateMind/debatemind/server.py
-
curl -L -o server.py https://huggingface.co/spaces/Smzu890/DebateMind/resolve/main/debatemind/server.py
7.25 kB
| """FastAPI MCP Server for DebateMind parliamentary simulation. | |
| Exposes Gymnasium-style environment endpoints (reset, step, state) and | |
| five MCP tool endpoints over HTTP. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import asdict | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from debatemind.environment import ParliamentEnvironment | |
| from debatemind.models.api import ( | |
| ActionRequest, | |
| CheckVoteTallyResponse, | |
| NegotiateRequest, | |
| NegotiateResponse, | |
| ObservationResponse, | |
| ProposeAmendmentRequest, | |
| ProposeAmendmentResponse, | |
| ReadTranscriptRequest, | |
| ReadTranscriptResponse, | |
| ResetConfig, | |
| SearchPrecedentRequest, | |
| SearchPrecedentResponse, | |
| StepResponse, | |
| ) | |
| from debatemind.models.observation import Observation | |
| from debatemind.tools.check_vote_tally import check_vote_tally as _check_vote_tally | |
| from debatemind.tools.negotiate import negotiate as _negotiate | |
| from debatemind.tools.propose_amendment import propose_amendment as _propose_amendment | |
| from debatemind.tools.read_transcript import read_transcript as _read_transcript | |
| from debatemind.tools.search_precedent import search_precedent as _search_precedent | |
| app = FastAPI(title="DebateMind MCP Server") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Global environment instance | |
| _env: ParliamentEnvironment | None = None | |
| def _get_env() -> ParliamentEnvironment: | |
| """Return the global environment, raising 400 if not initialized.""" | |
| if _env is None: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="Environment not initialized. Call /reset first.", | |
| ) | |
| return _env | |
| def _observation_to_response(obs: Observation) -> ObservationResponse: | |
| """Convert an Observation dataclass to an ObservationResponse Pydantic model.""" | |
| public_faction_stances = { | |
| fid: { | |
| "faction_id": stance.faction_id, | |
| "name": stance.name, | |
| "public_priorities": stance.public_priorities, | |
| "trust_score": stance.trust_score, | |
| "current_position": stance.current_position, | |
| } | |
| for fid, stance in obs.public_faction_stances.items() | |
| } | |
| transcript_last_3 = [ | |
| { | |
| "turn": entry.turn, | |
| "actor": entry.actor, | |
| "action_type": entry.action_type, | |
| "content": entry.content, | |
| } | |
| for entry in obs.transcript_last_3_turns | |
| ] | |
| deals = [ | |
| { | |
| "turn": deal.turn, | |
| "factions": deal.factions, | |
| "terms": deal.terms, | |
| "status": deal.status, | |
| } | |
| for deal in obs.deals_on_record | |
| ] | |
| amendments = [ | |
| { | |
| "clause_index": a.clause_index, | |
| "original_text": a.original_text, | |
| "new_text": a.new_text, | |
| "proposed_by": a.proposed_by, | |
| "turn_proposed": a.turn_proposed, | |
| } | |
| for a in obs.amendments_pending | |
| ] | |
| return ObservationResponse( | |
| turn=obs.turn, | |
| current_reading=obs.current_reading, | |
| bill_summary=obs.bill_summary, | |
| contested_clauses=obs.contested_clauses, | |
| public_faction_stances=public_faction_stances, | |
| vote_projection=obs.vote_projection, | |
| transcript_last_3_turns=transcript_last_3, | |
| deals_on_record=deals, | |
| amendments_pending=amendments, | |
| ) | |
| # --- Environment endpoints --- | |
| async def reset_env(config: ResetConfig | None = None) -> ObservationResponse: | |
| """Initialize a new parliamentary session.""" | |
| global _env | |
| _env = ParliamentEnvironment() | |
| bill_config = None | |
| if config is not None and (config.bill_title or config.bill_clauses): | |
| bill_config = {} | |
| if config.bill_title: | |
| bill_config["title"] = config.bill_title | |
| if config.bill_clauses: | |
| bill_config["clauses"] = config.bill_clauses | |
| obs = _env.reset(bill_config=bill_config) | |
| return _observation_to_response(obs) | |
| async def step_env(action: ActionRequest) -> StepResponse: | |
| """Advance the simulation by one turn.""" | |
| env = _get_env() | |
| action_dict = {} | |
| if action.tool_name is not None: | |
| action_dict["tool_name"] = action.tool_name | |
| if action.tool_args is not None: | |
| action_dict["tool_args"] = action.tool_args | |
| if action.speech is not None: | |
| action_dict["speech"] = action.speech | |
| obs, reward, done, info = env.step(action_dict) | |
| return StepResponse( | |
| observation=_observation_to_response(obs), | |
| reward=reward, | |
| done=done, | |
| info=info, | |
| ) | |
| async def get_state() -> ObservationResponse: | |
| """Return the current observation without advancing.""" | |
| env = _get_env() | |
| obs = env.state() | |
| return _observation_to_response(obs) | |
| async def health() -> dict: | |
| """Return health status.""" | |
| return {"status": "ok"} | |
| # --- Tool endpoints --- | |
| async def search_precedent(req: SearchPrecedentRequest) -> SearchPrecedentResponse: | |
| """Search historical parliamentary precedents.""" | |
| result = _search_precedent(req.topic) | |
| return SearchPrecedentResponse(precedents=result["precedents"]) | |
| async def propose_amendment(req: ProposeAmendmentRequest) -> ProposeAmendmentResponse: | |
| """Propose an amendment to a bill clause.""" | |
| env = _get_env() | |
| result = _propose_amendment( | |
| clause_index=req.clause_index, | |
| new_text=req.new_text, | |
| bill_sm=env.bill_sm, | |
| turn=env.turn, | |
| ) | |
| return ProposeAmendmentResponse( | |
| success=result["success"], | |
| amendment=result.get("amendment", {}), | |
| error=result.get("error"), | |
| ) | |
| async def negotiate(req: NegotiateRequest) -> NegotiateResponse: | |
| """Negotiate with a faction.""" | |
| env = _get_env() | |
| result = _negotiate( | |
| faction_id=req.faction_id, | |
| offer=req.offer, | |
| factions=env.factions, | |
| ) | |
| if "error" in result: | |
| return NegotiateResponse( | |
| score=0.0, | |
| trust_score=0.0, | |
| error=result["error"], | |
| ) | |
| return NegotiateResponse( | |
| score=result["score"], | |
| trust_score=result["trust_score"], | |
| ) | |
| async def read_transcript(req: ReadTranscriptRequest) -> ReadTranscriptResponse: | |
| """Read transcript entries for a turn range.""" | |
| env = _get_env() | |
| result = _read_transcript( | |
| start_turn=req.start_turn, | |
| end_turn=req.end_turn, | |
| transcript=env.transcript, | |
| ) | |
| return ReadTranscriptResponse(entries=result["entries"]) | |
| async def check_vote_tally() -> CheckVoteTallyResponse: | |
| """Check current projected vote counts with noise.""" | |
| env = _get_env() | |
| result = _check_vote_tally( | |
| factions=env.factions, | |
| bill=env.bill, | |
| vote_engine=env.vote_engine, | |
| rng=env.rng, | |
| ) | |
| return CheckVoteTallyResponse( | |
| projections=result["projections"], | |
| threshold=result["threshold"], | |
| ) | |