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

Aberta
#8,719 0 comentários 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 2 dias

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
4/5
Tempo estimado
3-5 dias
Facilidade para iniciantes
48/100
Tipo de issue
Bug
Clareza
Razoavelmente clara
Status de atividade
Ativa
Stack de tecnologia
javascript, json
Domínio
api

Direção de pesquisa

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.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

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.
Linguagem predominante
C++
Estrelas
1.3k
Forks
304
Merge médio
2d 20h
PRs com merge (30d)
10

Preparar o ambiente

Este projeto não oferece contêiner de desenvolvimento, Dockerfile nem guia de contribuição, então a configuração fica por sua conta: comece pelo README e veja nosso guia da primeira contribuição para os passos gerais.

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de Vector35/binaryninja-api

Todas as issues de Vector35/binaryninja-api

Issues semelhantes

Mais issues de C++

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.