fix(mcp): sessionId loses precision in JavaScript JSON consumers

Aperta
#8,719 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 2 giorni

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
48/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
javascript, json
Ambito
api

Direzione di ricerca

The report identifies structuredContent.openItem.sessionId in the GUI MCP server response, but the server implementation is shipped inside the proprietary application and no source file or test is named. Start by locating the code that builds the bn_binary_view_set_active response and checking how it serializes sessionId; reproduce with an identifier above JavaScript’s safe-integer limit. Done means JavaScript can recover the exact identifier while opaque handle selection still works.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Summary

The GUI MCP server emits structuredContent.openItem.sessionId as a bare JSON integer above JavaScript's safe-integer range. Parsing the raw HTTP reply with JSON.parse changes its exact integer value. This is an interoperability defect in emitted metadata, not a claim that the JSON syntax is invalid or that opaque openItem handles stop working.

Steps to reproduce

  1. Save the C source below as fixture.c, compile it, and open fixture in Binary Ninja. Enable and start the built-in GUI MCP server, then connect an MCP client and run tools/list.
#include <stdio.h>
volatile int fixture_global = 7;
__attribute__((noinline, used)) int fixture_leaf(int value) { puts("FIXTURE_LEAF"); return value + fixture_global; }
__attribute__((noinline, used)) int fixture_branch(int value) { return value > 3 ? fixture_leaf(value) : fixture_leaf(-value); }
int main(int argc, char **argv) { return fixture_branch(argc); }
clang -arch arm64 -O0 -g -fno-inline fixture.c -o fixture
  1. Call bn_binary_view_list, select the returned Mach-O view with bn_binary_view_set_active, and wait until bn_analysis_status reports IdleState. Use the returned handle unchanged; handle values are session-scoped.

  2. Capture a raw HTTP reply from bn_binary_view_set_active before a JavaScript JSON parser touches it. The following Python standard-library script initializes a separate MCP connection, retains MCP-Session-Id, lists tools and views, selects the returned Mach-O handle, and saves the response bytes as reply.raw. Run it in a disposable directory while the fixture is open. It does not execute the target or save a database.

import json
import urllib.request
from pathlib import Path

url = "http://127.0.0.1:24642/mcp"
headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
def send(method, params=None, request_id=1):
    message = {"jsonrpc": "2.0", "method": method}
    if request_id is not None:
        message["id"] = request_id
    if params is not None:
        message["params"] = params
    request = urllib.request.Request(url, json.dumps(message).encode(), headers)
    with urllib.request.urlopen(request) as response:
        return response.headers, response.read()
def decode(raw):
    text = raw.decode()
    if text.startswith(("event:", "data:")):
        text = "\n".join(line[5:].strip() for line in text.splitlines() if line.startswith("data:"))
    return json.loads(text)
response_headers, _ = send("initialize", {"protocolVersion": "2025-11-25", "capabilities": {}, "clientInfo": {"name": "repro", "version": "1"}})
headers["MCP-Session-Id"] = response_headers["MCP-Session-Id"]
send("notifications/initialized", request_id=None)
send("tools/list", {})
_, listing = send("tools/call", {"name": "bn_binary_view_list", "arguments": {}})
text = decode(listing)["result"]["content"][0]["text"]
rows = [[cell.strip() for cell in line.strip().strip("|").split("|")] for line in text.splitlines() if line.startswith("|")]
handle = next(row[0] for row in rows if row[2] == "Mach-O")
_, raw = send("tools/call", {"name": "bn_binary_view_set_active", "arguments": {"binaryView": handle}})
Path("reply.raw").write_bytes(raw)
  1. Run this JavaScript against those saved bytes. It isolates the numeric token in structuredContent and compares its exact integer value with the already-parsed JavaScript number, without publishing the generated identifier.
const fs = require('fs');
const raw = fs.readFileSync('reply.raw', 'utf8');
const json = raw.startsWith('event:') || raw.startsWith('data:')
  ? raw.split('\n').filter(line => line.startsWith('data:')).map(line => line.slice(5).trim()).join('\n')
  : raw;
const token = json.match(/"structuredContent"[\s\S]*?"sessionId"\s*:\s*(\d+)/)[1];
const id = JSON.parse(json).result.structuredContent.openItem.sessionId;
console.log('raw sessionId above MAX_SAFE_INTEGER:', BigInt(token) > BigInt(Number.MAX_SAFE_INTEGER));
console.log('Number.isSafeInteger(parsed):', Number.isSafeInteger(id));
console.log('BigInt(parsed) === BigInt(raw):', BigInt(id) === BigInt(token));

Expected behavior

An identifier exposed to MCP JSON clients should retain its exact value through supported JSON consumption. The guide explicitly formats output addresses as strings to avoid losing 64-bit precision, but does not document a precision-loss exception for sessionId. RFC 8259 section 6 describes the interoperable exact-integer range for binary64 consumers; it does not prohibit larger JSON number tokens.

Actual behavior

Raw HTTP bytes confirmed that the property was a bare decimal JSON number, not a quoted decimal string. The generated value exceeded Number.MAX_SAFE_INTEGER. The JavaScript check printed:

raw sessionId above MAX_SAFE_INTEGER: true
Number.isSafeInteger(parsed): false
BigInt(parsed) === BigInt(raw): false

The text field of the same response contained the original digits inside its JSON-encoded string, and bn_open_item_list displayed those digits in its Markdown table. The loss occurs when parsing the numeric structuredContent field with JavaScript's normal JSON parser. This was observed for one disposable fixture's generated identifier; frequency across other identifiers is unmeasured. Generated identifier values and local paths are intentionally omitted from this public report.

Evidence

  • Expected source: JSON interoperability guidance above and the MCP guide's output-address precision convention, linked under Runtime or environment; sessionId has no separate documented precision contract.
  • Failure source: Raw HTTP response bytes from the view-selection tool and the executed JavaScript token-versus-parsed-integer comparison shown above.
  • Evidence provenance: observed
  • Local verification: reproduced
  • Reproduction completeness: complete

Restoration check

Capture the same response before JSON parsing and verify that a normal JavaScript JSON consumer can recover the exact emitted identifier value. Include a generated identifier above the binary64 safe-integer range as a control; passing only with a smaller identifier would not cover the observed failure. Preserve normal opaque-handle selection behavior.

Runtime or environment

  • Binary Ninja Version: Free 6.0.10905-Stable; bundle version 6.0.10905_free; built-in GUI HTTP MCP server binaryninja_ui_mcp version 0.1.0.
  • Edition: Free. OS: macOS 27.2; CPU architecture: arm64. Target: thin arm64 Mach-O built with the command above. Analysis status was IdleState before the observations.
  • The official stable release metadata matched the installed build. A fresh profile enabled ui.mcp.enabled; no user plugins or existing databases were involved. The target was analyzed, never executed, and no database was saved.
  • The stable MCP guide and the current default-branch MCP guide were compared. Their relevant calling conventions agree. The implementation ships inside the proprietary application, so public default-branch source inspection does not verify its runtime behavior.
  • The issue template requests development-build testing. That was not performed: Free cannot switch to the development channel. Personal/Commercial editions, development builds, Windows, and Linux are untested.

Triage assessment

  • Impact level: P2
  • Assessment status: supported
  • Impact basis: Normal JavaScript JSON consumption silently changes the exact identifier in structured metadata for the observed value. No failed handle operation, collision, database corruption, or analysis error was observed.
  • Workaround status: available
  • Workaround basis: The exact digits remained in the reply's text string and in the open-item list's Markdown table; a client can preserve them as text. Python's arbitrary-precision JSON parser also retained the raw integer. These avoid the observed numeric precision loss without changing the binary or server.
Lingua principale
C++
Stelle
1.3k
Fork
304
Merge medio
2g 20h
PR unite (30g)
10

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di Vector35/binaryninja-api

Tutte le issue di Vector35/binaryninja-api

Issue simili

Altre issue su C++

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.