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
This commit is contained in:
1 parent
5bc1815ebc
commit
46ae7046ea
2 files changed
+68
-5
No files matched your search
+52
-3
@@ -17,18 +17,41 @@ Register in your harness's MCP config - e.g. ~/.omp/agent/mcp.json (stdio):
|
||||
|
||||
(!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: omp !cmd env values may arrive with the file's
|
||||
# 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(
|
||||
@@ -50,21 +73,47 @@ def omniparse(image_path: str = '', image_b64: str = '', format: str = 'view',
|
||||
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=300)
|
||||
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()
|
||||
d.pop('som_png_b64', None) if not include_som else None
|
||||
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__':
|
||||
|
||||
+16
-2
@@ -95,6 +95,7 @@ def _cache_key(raw: bytes, req) -> str:
|
||||
|
||||
|
||||
def _run_cached(key: str, raw: bytes, req) -> dict:
|
||||
t0 = time.perf_counter()
|
||||
eng: ParseEngine = STATE['engine']
|
||||
cached = STATE['cache'].get(key)
|
||||
hit = cached is not None
|
||||
@@ -119,7 +120,13 @@ def _run_cached(key: str, raw: bytes, req) -> dict:
|
||||
STATE['cache'].popitem(last=False)
|
||||
res = dict(res)
|
||||
out = {'image_size': res['image_size'], 'n_elements': len(res['elements']),
|
||||
'timings': res['timings'], 'cache_hit': hit}
|
||||
# a cache hit must never replay the original parse's timings as if
|
||||
# they were computed now - report them as history + fresh served_ms
|
||||
'timings': ({'served_from_cache': True,
|
||||
'original_parse': res['timings']}
|
||||
if hit else res['timings']),
|
||||
'served_ms': round((time.perf_counter() - t0) * 1000, 1),
|
||||
'cache_hit': hit}
|
||||
if req.format in ('full', 'both'):
|
||||
out['elements'] = res['elements']
|
||||
if req.format in ('view', 'both'):
|
||||
@@ -129,11 +136,18 @@ def _run_cached(key: str, raw: bytes, req) -> dict:
|
||||
return out
|
||||
|
||||
|
||||
@app.get('/', include_in_schema=False)
|
||||
async def root():
|
||||
return {'service': 'omniparse', 'health': '/healthz', 'docs': '/docs',
|
||||
'parse': 'POST /parse'}
|
||||
|
||||
|
||||
@app.post('/parse')
|
||||
async def parse(req: ParseReq, authorization: str | None = Header(None)):
|
||||
_auth(authorization)
|
||||
if not STATE['ready']:
|
||||
raise HTTPException(503, 'models still loading - see /healthz')
|
||||
raise HTTPException(503, 'models still loading - see /healthz',
|
||||
headers={'Retry-After': '10'})
|
||||
if isinstance(STATE['engine'], Exception):
|
||||
raise HTTPException(500, f'model load failed: {STATE["engine"]}')
|
||||
raw = req.image_b64.split(',', 1)[-1]
|
||||
|
||||
Reference in new issue
Block a user