Files
omniparse-mcp/omni_api/mcp_server.py
T
plean 46ae7046ea Surface tool failures; timeout discipline; call logging; cache-hit honesty
1. mcp shim: anticipate OSError/RequestException/JSON errors and raise
   ToolError with 'Type: message' - the SDK strips ALL text from bare
   exceptions ('Error executing tool omniparse' with zero detail)
2. shim HTTP timeout 300s -> 100s, below the harness's 120s: harness
   aborts are detailless, ours say why (documented)
3. shim file logging to ~/.cache/omniparse/mcp.log (harnesses discard
   stdio stderr): every call's args/status/duration + full tracebacks
4. warm-up 503 sends Retry-After: 10 (429 already did)
5. cache hits no longer replay original timings as live: timings become
   {served_from_cache, original_parse}, fresh served_ms on every response
6. token filename canonicalized on omniparse_token (deployed file real,
   not a symlink; harness config updated)
7. GET / points at /healthz and /docs instead of bare 404
2026-11-18 03:00:17 +00:00

121 lines
5.1 KiB
Python

"""MCP (Model Context Protocol) stdio shim for the omniparse REST service.
Registers one tool, `omniparse`, that forwards to POST /parse on the HTTP
service, so MCP-capable harnesses (omp /mcp.json, Claude Desktop, Cursor...)
get the parser as a first-class tool without custom plugin code.
Register in your harness's MCP config - e.g. ~/.omp/agent/mcp.json (stdio):
"omniparse": {
"command": "<repo>/.venv/bin/python",
"args": ["-m", "omni_api.mcp_server"],
"cwd": "<repo>",
"timeout": 120000,
"env": { "OMNI_API_URL": "http://127.0.0.1:8898",
"OMNI_API_TOKEN": "!cat /home/YOU/.config/omniparse_token" }
}
(!cmd values are executed at connect time without a shell - use an absolute
path; a bare env name copies the harness's variable or ships it literally.)
Timeout discipline: the HTTP timeout below (_HTTP_TIMEOUT_S = 100) MUST stay
below the harness tool timeout (120 s in the example above) - if the harness
aborts first, the failure it reports is detailless; an abort from here says
why. Raise both together if you have genuinely slow cold starts.
stdio stderr is discarded by most harnesses, so everything worth knowing
(every call, status, duration, full tracebacks of caught failures) goes to
~/.cache/omniparse/mcp.log, not the terminal.
"""
import base64
import logging
import os
import time
import traceback
import requests
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
API = os.environ.get('OMNI_API_URL', 'http://127.0.0.1:8898').rstrip('/')
_HTTP_TIMEOUT_S = 100 # keep below the harness timeout, see module docstring
_LOG_DIR = os.path.expanduser(
os.environ.get('OMNI_MCP_LOG_DIR', '~/.cache/omniparse'))
os.makedirs(_LOG_DIR, exist_ok=True)
log = logging.getLogger('omniparse-mcp')
log.setLevel(logging.INFO)
_fh = logging.FileHandler(os.path.join(_LOG_DIR, 'mcp.log'))
_fh.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
log.addHandler(_fh)
def _token() -> str:
# strip both branches: harness !cmd env values may arrive with the file's
# trailing newline, and a \n in a Bearer header trips httpx validation
return (os.environ.get('OMNI_API_TOKEN') or
open(os.path.expanduser(os.environ.get(
'OMNI_TOKEN_FILE', '~/.config/omniparse_token'))).read()).strip()
mcp = MCPServer('omniparse')
@mcp.tool()
def omniparse(image_path: str = '', image_b64: str = '', format: str = 'view',
include_som: bool = False) -> dict:
"""Parse a GUI screenshot into numbered, captioned interactable elements.
Give the screenshot as image_path (local file the agent can read, e.g. a
captured VM/desktop screenshot) OR image_b64 (base64 PNG/JPEG). Returns
elements: compact 'view' lines (id + pixel center + caption - the primary
LLM-facing form), and/or 'full' per-element JSON with normalized bbox and
center. Set include_som=true only when a vision model or a human must see
the annotated Set-of-Mark rendering. Click targets use center_px scaled to
the ACTUAL screen (image_size tells you the parsed resolution)."""
t0 = time.perf_counter()
args_desc = (f'path={image_path!r}' if image_path
else f'b64[{len(image_b64)} chars]' if image_b64 else 'no-input')
try:
if image_path:
b64 = base64.b64encode(open(image_path, 'rb').read()).decode()
elif image_b64:
b64 = image_b64
else:
log.info('call(%s, fmt=%s) -> rejected: no image input',
args_desc, format)
return {'error': 'provide image_path or image_b64'}
r = requests.post(f'{API}/parse',
json={'image_b64': b64, 'format': format,
'include_som': include_som},
headers={'Authorization': f'Bearer {_token()}'},
timeout=_HTTP_TIMEOUT_S)
if r.status_code != 200:
log.info('call(%s, fmt=%s) -> HTTP %s in %.1fs: %s', args_desc,
format, r.status_code, time.perf_counter() - t0,
r.text[:200])
return {'error': f'{r.status_code}: {r.text[:200]}'}
try:
d = r.json()
except ValueError as e:
log.error('call(%s) -> non-JSON body: %s', args_desc, r.text[:200])
raise ToolError(f'service returned non-JSON: {e}') from e
if not include_som:
d.pop('som_png_b64', None)
log.info('call(%s, fmt=%s) -> ok: %s elements (cache_hit=%s) in %.1fs',
args_desc, format, d.get('n_elements'), d.get('cache_hit'),
time.perf_counter() - t0)
return d
except ToolError:
raise
except (OSError, requests.RequestException) as e:
# ToolError text reaches the model; a bare exception would be stripped
# to "Error executing tool omniparse" by the SDK (see its exceptions.py)
log.error('call(%s, fmt=%s) FAILED after %.1fs:\n%s', args_desc,
format, time.perf_counter() - t0, traceback.format_exc())
raise ToolError(f'{type(e).__name__}: {e}') from e
if __name__ == '__main__':
mcp.run(transport='stdio')