File size: 6,382 Bytes
5233b57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
dispatchAI MCP Server - gives the agent tools to interact with the phone farm API.
This is a simple MCP server that exposes the dispatchAI API as tools.
"""
import json
import httpx
import asyncio
from typing import Any

# MCP server using the simple JSON-RPC protocol
# This runs as a subprocess that Hermes communicates with via stdio

BASE_URL = "http://127.0.0.1:8081"
API_KEY = "da-demo-key-0001"

TOOLS = [
    {
        "name": "chat_completion",
        "description": "Send a chat completion request to a dispatchAI model running on a phone. Returns the model's response.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "message": {"type": "string", "description": "The user message to send"},
                "model": {"type": "string", "description": "Model name (default: SmolLM2-135M)", "default": "dispatchAI/SmolLM2-135M-Instruct-mobile"},
                "max_tokens": {"type": "integer", "description": "Max tokens to generate", "default": 100},
            },
            "required": ["message"],
        },
    },
    {
        "name": "list_models",
        "description": "List all available dispatchAI models",
        "inputSchema": {"type": "object", "properties": {}},
    },
    {
        "name": "get_phone_status",
        "description": "Get the status of the phone farm - how many phones are connected and their load",
        "inputSchema": {"type": "object", "properties": {}},
    },
    {
        "name": "get_api_usage",
        "description": "Get API usage statistics for the current API key",
        "inputSchema": {"type": "object", "properties": {}},
    },
]


async def call_tool(name: str, arguments: dict) -> str:
    """Call a tool and return the result."""
    async with httpx.AsyncClient(timeout=120.0) as client:
        if name == "chat_completion":
            model = arguments.get("model", "dispatchAI/SmolLM2-135M-Instruct-mobile")
            message = arguments.get("message", "")
            max_tokens = arguments.get("max_tokens", 100)

            r = await client.post(
                f"{BASE_URL}/v1/chat/completions",
                headers={
                    "Content-Type": "application/json",
                    "Authorization": f"Bearer {API_KEY}",
                },
                json={
                    "model": model,
                    "messages": [{"role": "user", "content": message}],
                    "max_tokens": max_tokens,
                },
            )
            if r.status_code == 200:
                data = r.json()
                content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
                phone = data.get("phone_info", {})
                usage = data.get("usage", {})
                return json.dumps({
                    "response": content,
                    "phone": phone.get("serial", "unknown"),
                    "speed_tps": phone.get("generation_tps", 0),
                    "tokens_used": usage.get("total_tokens", 0),
                })
            else:
                return f"Error: {r.status_code} - {r.text[:200]}"

        elif name == "list_models":
            r = await client.get(
                f"{BASE_URL}/v1/models",
                headers={"Authorization": f"Bearer {API_KEY}"},
            )
            if r.status_code == 200:
                data = r.json()
                models = [m["id"] for m in data.get("data", [])]
                return json.dumps({"models": models})
            return f"Error: {r.status_code}"

        elif name == "get_phone_status":
            r = await client.get(
                f"{BASE_URL}/admin/phones",
                headers={"Authorization": f"Bearer {API_KEY}"},
            )
            if r.status_code == 200:
                return json.dumps(r.json())
            return f"Error: {r.status_code}"

        elif name == "get_api_usage":
            r = await client.get(
                f"{BASE_URL}/v1/usage",
                headers={"Authorization": f"Bearer {API_KEY}"},
            )
            if r.status_code == 200:
                return json.dumps(r.json())
            return f"Error: {r.status_code}"

    return f"Unknown tool: {name}"


# Simple MCP JSON-RPC server over stdio
import sys

def main():
    """Main MCP server loop - reads JSON-RPC from stdin, writes to stdout."""
    while True:
        try:
            line = sys.stdin.readline()
            if not line:
                break

            req = json.loads(line)
            method = req.get("method", "")
            req_id = req.get("id")

            if method == "initialize":
                resp = {
                    "jsonrpc": "2.0",
                    "id": req_id,
                    "result": {
                        "protocolVersion": "2024-11-05",
                        "capabilities": {"tools": {}},
                        "serverInfo": {"name": "dispatchai-mcp", "version": "1.0.0"},
                    },
                }
                sys.stdout.write(json.dumps(resp) + "\n")
                sys.stdout.flush()

            elif method == "tools/list":
                resp = {
                    "jsonrpc": "2.0",
                    "id": req_id,
                    "result": {"tools": TOOLS},
                }
                sys.stdout.write(json.dumps(resp) + "\n")
                sys.stdout.flush()

            elif method == "tools/call":
                params = req.get("params", {})
                tool_name = params.get("name", "")
                arguments = params.get("arguments", {})

                result = asyncio.run(call_tool(tool_name, arguments))

                resp = {
                    "jsonrpc": "2.0",
                    "id": req_id,
                    "result": {
                        "content": [{"type": "text", "text": result}]
                    },
                }
                sys.stdout.write(json.dumps(resp) + "\n")
                sys.stdout.flush()

        except Exception as e:
            if req_id:
                resp = {
                    "jsonrpc": "2.0",
                    "id": req_id,
                    "error": {"code": -32603, "message": str(e)},
                }
                sys.stdout.write(json.dumps(resp) + "\n")
                sys.stdout.flush()


if __name__ == "__main__":
    main()