Every example below connects to https://api.nexus402.dev/v1/mcp over streamable HTTP, sends your key in the X-Nexus-Api-Key header, lists the tools the key may call, and calls the one you name in NEXUS402_TOOL. A call to a paid tool is charged to your wallet. If you name none, nothing is called. Each is run against a test gateway at the version shown, so a framework release that changes how headers are passed is caught before you meet it.
For an agent that should find tools itself instead of loading every schema, use https://api.nexus402.dev/v1/mcp/meta with the same key: see agents.
A call your wallet cannot pay for is refused with HTTP 402 and nothing is charged; each example prints call refused and exits with code 2.
MCP Python SDK #
Python, mcp 1.30.0 (tested). Give the SDK an httpx.AsyncClient that carries the header.
Its own page.
pip install -r requirements.txt
export NEXUS402_API_KEY=nx_dev_...
# The tool to call, by its name in the marketplace. A paid tool is charged.
export NEXUS402_TOOL='<tool name>'
python main.py
"""Call a Nexus402 tool with the official MCP Python SDK (ADR-0236).
The key comes from NEXUS402_API_KEY and travels in the X-Nexus-Api-Key
header. It is never written in code. NEXUS402_TOOL names the tool to call
(required: a call is charged) and NEXUS402_ARGS its JSON arguments.
"""
import asyncio
import json
import os
import sys
import httpx
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
URL = os.environ.get("NEXUS402_MCP_URL", "https://api.nexus402.dev/v1/mcp")
TOOL = os.environ.get("NEXUS402_TOOL", "")
def refusal(error: BaseException) -> httpx.HTTPStatusError | None:
"""The HTTP refusal inside an error, however deeply the SDK grouped it."""
if isinstance(error, httpx.HTTPStatusError):
return error
if isinstance(error, BaseExceptionGroup):
for inner in error.exceptions:
found = refusal(inner)
if found is not None:
return found
return None
async def main() -> int:
# The SDK raises an HTTP refusal (a 402 when the wallet cannot pay) from
# its transport's task group, so it surfaces here, as an ExceptionGroup,
# rather than from call_tool.
try:
return await call()
except Exception as error:
refused = refusal(error)
if refused is None:
raise
print(f"call refused: HTTP {refused.response.status_code}")
return 2
async def call() -> int:
headers = {"X-Nexus-Api-Key": os.environ["NEXUS402_API_KEY"]}
async with httpx.AsyncClient(headers=headers, timeout=60) as http:
async with streamable_http_client(URL, http_client=http) as (read, write, _):
async with ClientSession(read, write) as session:
await session.initialize()
tools = (await session.list_tools()).tools
print(f"{len(tools)} tools listed")
args = json.loads(os.environ.get("NEXUS402_ARGS", "{}"))
try:
result = await session.call_tool(TOOL, args)
except Exception as error: # a 402 or another refusal
print(f"call refused: {error}")
return 2
if result.isError:
print(f"call refused: {result.content}")
return 2
for block in result.content:
print(getattr(block, "text", block))
return 0
if __name__ == "__main__":
# Never a default: a call is charged, and you choose who is paid.
if not TOOL:
sys.exit(
"Set NEXUS402_TOOL to the name of the tool to call. Nothing was called. "
"A call to a paid tool is charged to your wallet."
)
sys.exit(asyncio.run(main()))
LangChain (Python) #
Python, langchain-mcp-adapters 0.3.2 (tested). Put the header in the connection's headers; every tool the key may call becomes a LangChain tool.
Its own page.
pip install -r requirements.txt
export NEXUS402_API_KEY=nx_dev_...
# The tool to call, by its name in the marketplace. A paid tool is charged.
export NEXUS402_TOOL='<tool name>'
python main.py
"""Call a Nexus402 tool through LangChain's MCP adapters (ADR-0236).
The adapters turn every tool the key may call into a LangChain tool, so an
agent built with LangChain or LangGraph can use them directly. Here one is
invoked by hand: the one NEXUS402_TOOL names (required: a call is charged).
The key comes from NEXUS402_API_KEY, never from code.
"""
import asyncio
import json
import os
import sys
from langchain_mcp_adapters.client import MultiServerMCPClient
URL = os.environ.get("NEXUS402_MCP_URL", "https://api.nexus402.dev/v1/mcp")
TOOL = os.environ.get("NEXUS402_TOOL", "")
def routing_name(tool) -> str:
"""The tool's routing name (acme/weather/forecast), when the list names it
by its MCP-safe listed name (acme_weather_forecast, ADR-0264) and the
adapters keep the row's _meta. So NEXUS402_TOOL may be either spelling."""
meta = (getattr(tool, "metadata", None) or {}).get("_meta")
return meta.get("nexus402/name", "") if isinstance(meta, dict) else ""
async def main() -> int:
client = MultiServerMCPClient(
{
"nexus402": {
"transport": "streamable_http",
"url": URL,
"headers": {"X-Nexus-Api-Key": os.environ["NEXUS402_API_KEY"]},
}
},
handle_tool_errors=False,
)
tools = await client.get_tools()
print(f"{len(tools)} tools listed")
tool = next(t for t in tools if TOOL in (t.name, routing_name(t)))
args = json.loads(os.environ.get("NEXUS402_ARGS", "{}"))
try:
result = await tool.ainvoke(args)
except Exception as error: # a 402 or another refusal
print(f"call refused: {error}")
return 2
print(result)
return 0
if __name__ == "__main__":
# Never a default: a call is charged, and you choose who is paid.
if not TOOL:
sys.exit(
"Set NEXUS402_TOOL to the name of the tool to call. Nothing was called. "
"A call to a paid tool is charged to your wallet."
)
sys.exit(asyncio.run(main()))
OpenAI Agents SDK (Python) #
Python, openai-agents 0.25.0 (tested). Put the header in MCPServerStreamableHttp's params, then pass the server to an Agent's mcp_servers.
Its own page.
pip install -r requirements.txt
export NEXUS402_API_KEY=nx_dev_...
# The tool to call, by its name in the marketplace. A paid tool is charged.
export NEXUS402_TOOL='<tool name>'
python main.py
"""Call a Nexus402 tool through the OpenAI Agents SDK's MCP server (ADR-0236).
Pass the same server to an Agent (`Agent(..., mcp_servers=[server])`) and the
model can call any tool the key allows. Here one is called directly, so the
example needs no model: the one NEXUS402_TOOL names (required: a call is
charged). The key comes from NEXUS402_API_KEY, never from code.
"""
import asyncio
import json
import os
import sys
from agents.mcp import MCPServerStreamableHttp
URL = os.environ.get("NEXUS402_MCP_URL", "https://api.nexus402.dev/v1/mcp")
TOOL = os.environ.get("NEXUS402_TOOL", "")
async def main() -> int:
params = {"url": URL, "headers": {"X-Nexus-Api-Key": os.environ["NEXUS402_API_KEY"]}}
async with MCPServerStreamableHttp(params=params, name="nexus402") as server:
tools = await server.list_tools()
print(f"{len(tools)} tools listed")
args = json.loads(os.environ.get("NEXUS402_ARGS", "{}"))
try:
result = await server.call_tool(TOOL, args)
except Exception as error: # a 402 or another refusal
print(f"call refused: {error}")
return 2
# The SDK re-exports the MCP result; newer MCP releases name the flag is_error.
if getattr(result, "is_error", getattr(result, "isError", False)):
print(f"call refused: {result.content}")
return 2
for block in result.content:
print(getattr(block, "text", block))
return 0
if __name__ == "__main__":
# Never a default: a call is charged, and you choose who is paid.
if not TOOL:
sys.exit(
"Set NEXUS402_TOOL to the name of the tool to call. Nothing was called. "
"A call to a paid tool is charged to your wallet."
)
sys.exit(asyncio.run(main()))
MCP TypeScript SDK #
TypeScript, @modelcontextprotocol/sdk 1.32.2 (tested). Pass the header in the transport's requestInit.
Its own page.
npm install
export NEXUS402_API_KEY=nx_dev_...
# The tool to call, by its name in the marketplace. A paid tool is charged.
export NEXUS402_TOOL='<tool name>'
node main.ts
// Call a Nexus402 tool with the official MCP TypeScript SDK (ADR-0236).
//
// The key comes from NEXUS402_API_KEY and travels in the X-Nexus-Api-Key
// header; it is never written in code. NEXUS402_TOOL names the tool to call
// (required: a call is charged) and NEXUS402_ARGS its JSON arguments.
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
const url = process.env.NEXUS402_MCP_URL ?? "https://api.nexus402.dev/v1/mcp";
const key = process.env.NEXUS402_API_KEY;
if (!key) throw new Error("Set NEXUS402_API_KEY");
const name = process.env.NEXUS402_TOOL;
// Never a default: a call is charged, and you choose who is paid.
if (!name) {
throw new Error("Set NEXUS402_TOOL to the name of the tool to call. Nothing was called. A call to a paid tool is charged to your wallet.");
}
const client = new Client({ name: "nexus402-example", version: "1.0.0" });
await client.connect(new StreamableHTTPClientTransport(new URL(url), { requestInit: { headers: { "X-Nexus-Api-Key": key } } }));
const { tools } = await client.listTools();
console.log(`${tools.length} tools listed`);
const args = JSON.parse(process.env.NEXUS402_ARGS ?? "{}") as Record<string, unknown>;
let code = 0;
try {
const result = await client.callTool({ name, arguments: args });
if (result.isError) {
console.log(`call refused: ${JSON.stringify(result.content)}`);
code = 2;
} else {
for (const block of result.content as { type: string; text?: string }[]) console.log(block.text ?? JSON.stringify(block));
}
} catch (error) {
// A 402 or another refusal.
console.log(`call refused: ${String(error)}`);
code = 2;
}
await client.close();
// exitCode, not process.exit(): exiting while the transport's handles close
// aborts Node on Windows.
process.exitCode = code;