# MCP aur tool ecosystem: protocol kaise chalta hai, tools zyada hon to kya

> MCP AI apps ko external tools aur data se jodne wala open protocol hai; 2026-07-28 spec stateless hai. Yeh page real wire messages se protocol kholta hai, 96 tool definitions ka token cost naapta hai, aur teen tool-selection approaches compare karta hai।

- URL: https://dmxsf.com/hi/wiki/applications/mcp-and-tool-ecosystem/
- [DMXSF](https://dmxsf.com/hi/about/)
- मध्यम
- अपडेट किया गया: 2026-11-23
- Tags: Agents, Tool use, Safety & security

## यह पृष्ठ पूरा करने पर आप

- Saaf bataayein MCP integration solve karta hai, selection nahi: host, client, server ke roles, aur teen primitives mein se har ek ka use kaun decide karta hai।
- 2026-07-28 spec ka stateless connection padhein: na handshake na session; har request apne _meta mein sab kuch le jaati hai; version server/discover se negotiate hota hai।
- Protocol errors aur tool execution errors alag karein; aise error messages likhein jo model khud sudhaar sake।
- Jaanein Streamable HTTP ke header validation, Origin validation aur authorization framework har ek kya rokte hain; aur local servers, token passthrough jaise common attack surfaces।
- Tool definitions kitne tokens lete hain, nikaalein; BM25 retrieval aur index-then-inspect se 96 tools ko kuch sau se ek-hazaar-plus tokens tak ghataayein, aur iski accuracy keemat naapein।
- Tool count aur definition size ke hisaab se full-context, retrieval, progressive disclosure aur code mode mein se chunein; har ek ka prompt-cache asar bhi batayein।

MCP (Model Context Protocol) AI apps ko external systems se jodne wala open protocol hai: external system ek baar server implement karta hai, aur saare MCP-supporting apps uske tools discover aur call kar sakte hain, resources padh sakte hain, prompt templates use kar sakte hain. Yeh **integration** solve karta hai, **selection** nahi: protocol yeh nahi tay karta kaun se tools model tak jaayein, aur model sahi chunta hai ya nahi. 2026-07-28 spec protocol ko stateless bana deti hai - handshake aur session khatam. Yeh page pehle real wire messages se protocol kholta hai, phir naapta hai 96 tools ki definitions kitne tokens leti hain, aur full-context, retrieval, progressive disclosure compare karta hai।

## Do hisaab: integration cost aur context cost

Protocol na ho to N apps ko M external systems - N x M adapters; protocol ho to har system ek server, har app ek client - kaam N+M. Yehi MCP ki value hai, aur November 2024 launch ke baad apps ne jaldi adopt kiya: Anthropic ne 2025-12-09 ke [announcement](https://www.anthropic.com/news/donating-the-model-context-protocol-and-establishing-of-the-agentic-ai-foundation) mein kaha 10,000+ active public MCP servers hain, jo ChatGPT, Cursor, Gemini, Microsoft Copilot, Visual Studio Code jaise products adopt kar chuke hain (vendor-reported); usi din MCP ko Linux Foundation ke under Agentic AI Foundation ko donate kar diya।

Integration sasta hone ke baad doosra hisaab saamne aata hai: har tool ek definition (name, description, params JSON Schema) le jaata hai; kuch servers judaoge to definitions context bhar dengi. Anthropic ne 2025-11-24 ke [article](https://www.anthropic.com/research/advanced-tool-use) mein ek example diya: paanch servers ke 58 tools lagbhag 55K tokens - conversation shuru hone se pehle hi khatam; internally 134K tokens tak ke tool definitions dekhe (vendor-reported). MCP ke official [client best practices](https://modelcontextprotocol.io/docs/2026-07-28/develop/clients/client-best-practices) bhi isi ko problem maante hain: saare definitions ek saath context mein dalne se tokens waste, latency badhti hai, model performance girti hai।

To yeh page do sawaalon ke saath padho: protocol khud kaise chalta hai, aur protocol jo solve nahi karta woh kaise. Official architecture docs clearly kehte hain: MCP sirf context-exchange protocol hai - AI app LLM kaise use kare, context kaise manage ho, yeh nahi batata।

| Pehlu | MCP manage karta hai | MCP nahi |
| --- | --- | --- |
| Integration | Tools discover/call, resources read, prompts lena ka unified message format | Model ko kaun se tools expose hon |
| Connection | Do transports (stdio, Streamable HTTP), version/capability negotiation | Model tools kaise chune, context kaise manage ho |
| Security | Authorization framework (OAuth 2.1), Origin validation, header validation | Koi ek call execute honi chahiye ya nahi; returns trustworthy hain ya nahi |

## Protocol ka poora naksha

### Participants aur layers

*Figure: Host har server ke liye ek client banata hai - one-to-one connections (official architecture docs ka kehna). Local servers usually ek hi client serve karte hain; remote servers kai clients. Protocol in lines ko manage karta hai - model tools kaise chunta hai, nahi।*

MCP client-server architecture hai, teen roles:

- **host**: AI app khud - jaise Claude Code, Visual Studio Code ya aapka likha Agent - ek ya kai clients coordinate karta hai;
- **client**: host ka component, kisi server ke saath connection rakhta hai, mila context host ko deta hai;
- **server**: context dene wala program - kahin bhi chale।

Host har server ke liye ek client banata hai, har ek ki dedicated connection. Protocol do layers mein: data layer JSON-RPC 2.0 par message protocol (discover, teen primitives, notifications); transport layer connection, framing, authorization. Do standard transports: **stdio** (host server ko child process ke roop mein start karta hai, stdin/stdout se baat; local server usually ek client) aur **Streamable HTTP** (client HTTP POST se messages; response JSON ya stream; remote servers usually kai clients)।

### Teen primitives: use kaun decide karta hai

Server teen primitives deta hai; spec har ek ke liye likhti hai "use kaun decide karta hai" - isse pata chalta hai woh kahan use hone chahiye:

| Primitive | Use kaun decide | Typical content | Discover aur use |
| --- | --- | --- | --- |
| Tools | Model (model-controlled) | DB query, API call, file write | `tools/list`, `tools/call` |
| Resources | Application (application-driven) | File contents, DB schema | `resources/list`, `resources/read` |
| Prompts | User (user-controlled) | Slash commands, reusable templates | `prompts/list`, `prompts/get` |

Spec tools ke liye ek aur requirement likhti hai: trust aur security ke liye **hamesha human-in-the-loop hona chahiye, tool calls reject karne ke kabil** (app model ko expose hue tools dikhaye, call par clear cue de, action requests par user confirmation maange). Client-side ek aur primitive: **elicitation** - server user se zyada info maang sakta hai. Roots, Sampling (server host ke model se completion maange) aur Logging ko 2026-07-28 mein deprecated mark kiya gaya; official advice: directories ke liye tool params ya resource URIs, model provider API seedha call karo, logs stderr ya OpenTelemetry se।

### Paanch versions

Spec versions dates se named hain. [Version changelog](https://modelcontextprotocol.io/specification/2026-07-28/changelog) se har version ke mukhya points - purani tutorials padhte waqt match karna:

| Version | Mukhya points |
| --- | --- |
| 2024-11-05 | Pehla public version (2024-11-25 publish); transports stdio aur HTTP+SSE |
| 2025-03-26 | OAuth 2.1-based authorization; Streamable HTTP ne HTTP+SSE replace; tool annotations (read-only, destructive waghera) |
| 2025-06-18 | Structured tool output; MCP servers ko OAuth resource servers classify; elicitation; `MCP-Protocol-Version` header |
| 2025-11-25 | Tool naming guidance; URL-mode elicitation; Client ID Metadata Documents; experimental tasks; illegal Origin par 403 clearly |
| 2026-07-28 | Stateless: handshake/session khatam; `server/discover`; `subscriptions/listen`; headers `Mcp-Method`, `Mcp-Name`; list results cache hints ke saath; Roots, Sampling, Logging deprecated |

Neeche ke experiment naya-purana dono zamane use karte hain: official Python SDK 2.3.0 ke client mein `legacy` (handshake era), `auto` (pehle probe) aur `2026-07-28` teen modes hain।

## Experiment 1: ek call wire par kaisi dikhti hai

Docs spec batate hain; yeh experiment wire par waqai guzarne wale bytes dekhta hai. Setup:

- Fictional company Acme ka backoffice banaya - 12 services (orders, billing, shipping, CRM, tickets, inventory, calendar, email, docs, HR, analytics, deploy), har service ke 8 tools, total 96; naam jaise `orders_cancel_order`;
- Server official SDK ke `MCPServer` se; tool functions catalog se auto-generate: sirf params validate, `ok` return - data aur logic dono demo;
- Client-server ke beech 19-line ka logging proxy - dono directions ki har JSON-RPC line, direction aur time ke saath log;
- Client official SDK ka `Client`, `legacy`, `auto`, `2026-07-28` teeno modes se connect; saare tools list; phir ek `orders_cancel_order` call।

> Neeche ke code blocks order se jodkar poora script banta hai. Environment: Apple M2 Max (64 GB), sirf CPU; Python 3.14.3, official SDK `mcp` 2.3.0 (version `setup` ke output mein), koi deep-learning framework nahi. Server aur proxy dono child processes, pipes se baat - network ports nahi (HTTP section ko chhod kar, jo 127.0.0.1 ke free port par sunta hai). Ek full run lagbhag 4 seconds; byte counts deterministic hain - sirf SDK version ke saath badlenge।

```python
import asyncio, json, os, platform, subprocess, sys, tempfile
import unicodedata
import importlib.metadata as md
from mcp import Client
from mcp.client.stdio import StdioServerParameters
from mcp_types.version import (HANDSHAKE_PROTOCOL_VERSIONS,
                               MODERN_PROTOCOL_VERSIONS)

print("python", platform.python_version(), "| mcp", md.version("mcp"))
print("handshake-era versions: "
      + ", ".join(HANDSHAKE_PROTOCOL_VERSIONS))
print("stateless-era versions: "
      + ", ".join(MODERN_PROTOCOL_VERSIONS))
WORK = tempfile.mkdtemp(prefix="mcp-")
PY = sys.executable

def pad(s, width):
    """Left-align s in width display columns (wide chars count 2)."""
    return s + " " * (width - sum(2 if unicodedata.east_asian_width(c) in "WF"
                                  else 1 for c in s))
```

```text
python 3.14.3 | mcp 2.3.0
handshake-era versions: 2024-11-05, 2025-03-26, 2025-06-18, 2025-11-25
stateless-era versions: 2026-07-28
```

Note: numbers original run se hain; print labels Latin transliteration mein likhe gaye hain।

Pehle tool catalog. Yeh data hai, algorithm nahi, isliye folded; `server` block ise temp directory mein likhta hai, server line-by-line padhta hai।

<details>
<summary>Expand: 96 tools ka catalog</summary>

```python
CATALOG = """
[orders]
get_order order_id:int; order ka status, items aur amount poochho
list_orders customer_id:int status:str; ek customer ke orders status se list karo
cancel_order order_id:int reason:str; jo ship nahi hua order cancel karo
update_order_address order_id:int address:str; order ka delivery address badlo
add_order_note order_id:int note:str; order par internal note jodo
return_order order_id:int reason:str; delivered item ka return register karo
reorder order_id:int; history order se dobara order karo
export_orders since:str; is date ke baad ke orders export (CSV)
[billing]
get_invoice invoice_id:int; invoice aur uski line items poochho
list_invoices customer_id:int; ek customer ke invoices list karo
create_invoice customer_id:int amount:float; customer ke liye invoice banao
void_invoice invoice_id:int; galat bana invoice void karo
issue_refund payment_id:str amount:float; ek payment ko original card par wapas karo
list_payments customer_id:int; customer ke payments list karo
update_payment_method customer_id:int method:str; default payment method badlo
cancel_subscription subscription_id:str; recurring subscription cancel karo
[shipping]
track_shipment tracking_no:str; package ki tracking timeline poochho
create_label order_id:int carrier:str; order ke liye shipping label khareedo
schedule_pickup order_id:int date:str; carrier se pickup book karo
cancel_pickup pickup_id:str; booked pickup cancel karo
change_delivery_date tracking_no:str date:str; carrier se delivery date badlwao
update_ship_address tracking_no:str address:str; in-transit package naye address par bhejo
list_carriers country:str; is country ko cover karne wale carriers list karo
get_shipping_rates weight_kg:float country:str; weight se shipping rates poochho
[crm]
get_contact contact_id:int; contact ka profile poochho
search_contacts query:str; naam ya email se contacts search karo
create_contact name:str email:str; naya contact banao
update_contact contact_id:int field:str value:str; contact ka ek field badlo
merge_contacts source_id:int target_id:int; do duplicate contacts merge karo
delete_contact contact_id:int; contact aur uska history delete karo
add_contact_note contact_id:int note:str; contact timeline par note jodo
list_segments; customer segments list karo
[tickets]
create_ticket title:str body:str; naya support ticket banao
get_ticket ticket_id:int; ticket aur uske comments poochho
update_ticket ticket_id:int field:str value:str; ticket ka ek field badlo
assign_ticket ticket_id:int assignee:str; ticket kisi agent ko assign karo
close_ticket ticket_id:int resolution:str; resolution likhkar ticket band karo
reopen_ticket ticket_id:int; band ticket dobara kholo
list_tickets status:str; status se tickets list karo
add_ticket_comment ticket_id:int comment:str; ticket ke neeche comment karo
[inventory]
get_stock sku:str; kisi SKU ka stock count poochho
reserve_stock sku:str quantity:int; order ke liye SKU stock reserve karo
release_stock reservation_id:str; ek stock reservation release karo
adjust_stock sku:str delta:int; audit ke baad stock count theek karo
list_warehouses; warehouses list karo
transfer_stock sku:str to_wh:str quantity:int; stock doosre warehouse mein bhejo
set_reorder_level sku:str level:int; SKU ka reorder threshold set karo
list_low_stock threshold:int; threshold se kam stock wale SKUs list karo
[calendar]
create_event title:str start:str; schedule event banao
list_events date:str; ek din ke events list karo
cancel_event event_id:str; event cancel karo
reschedule_event event_id:str start:str; event ka start time badlo
find_free_slot attendees:str duration_min:int; sab ke free slot dhoondo
add_attendee event_id:str email:str; kisi ko event mein bulaao
set_reminder event_id:str minutes:int; event se pehle reminder set karo
list_rooms; bookable meeting rooms list karo
[email]
send_email to:str subject:str body:str; email bhejo
search_emails query:str; mailbox search karo
get_email email_id:str; ek email padho
draft_reply email_id:str instructions:str; email ka draft reply banao
forward_email email_id:str to:str; email kisi ko forward karo
archive_email email_id:str; email archive mein daalo
list_labels; mailbox labels list karo
add_label email_id:str label:str; email par label lagao
[docs]
search_docs query:str; docs library search karo
get_doc doc_id:str; document padho
create_doc title:str content:str; document banao
update_doc doc_id:str content:str; document ka content replace karo
share_doc doc_id:str email:str; document kisi ke saath share karo
delete_doc doc_id:str; document delete karo
list_doc_versions doc_id:str; document ke past versions list karo
export_doc_pdf doc_id:str; document ko PDF export karo
[hr]
get_employee employee_id:int; employee profile poochho
request_leave employee_id:int start:str end:str; leave request submit karo
approve_leave request_id:str; leave request approve karo
cancel_leave request_id:str; leave request cancel karo
list_holidays year:int; saal ke public holidays list karo
get_leave_balance employee_id:int; bache leave days poochho
list_team manager_id:int; manager ke direct reports list karo
update_employee_phone employee_id:int phone:str; employee ka phone badlo
[analytics]
run_report report_id:str month:str; saved report run karo (monthly)
get_metric metric:str date:str; kisi din ka metric value poochho
list_reports; saved reports list karo
schedule_report report_id:str cron:str; report scheduled chalwao
cancel_report_schedule schedule_id:str; scheduled report rok do
export_report_csv report_id:str; report data CSV export karo
create_dashboard title:str; khaali dashboard banao
share_dashboard dashboard_id:str email:str; dashboard share karo
[deploy]
deploy_service service:str version:str; service ka specified version deploy karo
rollback_service service:str; service ko pichhle version par rollback karo
get_deploy_status deploy_id:str; ek deploy ka status poochho
list_services; deployable services list karo
restart_service service:str; service ke saare instances restart karo
scale_service service:str replicas:int; service ke instances ki ginti set karo
get_service_logs service:str lines:int; service ki recent log lines lo
cancel_deploy deploy_id:str; chalu deploy cancel karo
"""
rows = [r for r in CATALOG.strip().split("\n") if not r.startswith("[")]
print(f"services: {CATALOG.count(chr(10) + '[')}"
      f", tools: {len(rows)}")
```

```text
services: 12, tools: 96
```

</details>

Server khud sirf 33 lines. `check` dono failures ke prototypes: negative value = "expected failure" - SDK ka `ToolError`; zero = "kisi ne plan nahi kiya bug" - `RuntimeError`. Aage ke error experiments in dono functions se compare karte hain।

```python
SERVER = '''
import sys
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

mcp = MCPServer("acme-backoffice")

def check(name, value):
    if value < 0:                         # a failure we saw coming
        raise ToolError(f"{name} must be >= 0, got {value}")
    if value == 0:                        # a bug nobody planned for
        raise RuntimeError("database connection lost")
    return "ok"

service = None
for row in open(sys.argv[1], encoding="utf-8").read().strip().split("\\n"):
    if row.startswith("["):
        service = row.strip("[]")
        continue
    head, desc = row.split("; ", 1)
    name, *params = head.split()
    name, args = f"{service}_{name}", [p.split(":") for p in params]
    body = "return 'ok'"
    if args and args[0][1] == "int":
        body = f"return check('{args[0][0]}', {args[0][0]})"
    scope = {"check": check}
    exec(f"def {name}({', '.join(f'{a}: {t}' for a, t in args)}) -> str:\\n"
         f"    {body}", scope)
    scope[name].__doc__ = desc
    mcp.tool()(scope[name])

mcp.run()
'''

TEE = '''
import subprocess, sys, threading, time

log, cmd, t0 = open(sys.argv[1], "w"), sys.argv[2:], time.time()
srv = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                       stderr=subprocess.DEVNULL, text=True, bufsize=1)

def pump(src, dst, tag):
    for line in src:
        log.write(f"{time.time() - t0:.3f} {tag} {line}")
        log.flush()
        dst.write(line)
        dst.flush()
    dst.close()

a = threading.Thread(target=pump, args=(sys.stdin, srv.stdin, ">"))
b = threading.Thread(target=pump, args=(srv.stdout, sys.stdout, "<"))
a.start(), b.start(), a.join(), b.join(), srv.wait()
'''
for name, text in (("catalog.txt", CATALOG.strip()), ("server.py", SERVER),
                   ("tee.py", TEE)):
    open(os.path.join(WORK, name), "w", encoding="utf-8").write(text)
n_server, n_tee = (len(t.strip().split("\n")) for t in (SERVER, TEE))
print(f"server.py: {n_server} lines, tee.py: {n_tee} lines")
```

```text
server.py: 33 lines, tee.py: 19 lines
```

### Handshake era vs stateless era ka farq

```python
def argv(log):
    return [os.path.join(WORK, "tee.py"), log, PY,
            os.path.join(WORK, "server.py"), os.path.join(WORK, "catalog.txt")]

async def session(mode):
    log = os.path.join(WORK, f"{mode}.log")
    params = StdioServerParameters(command=PY, args=argv(log))
    async with Client(params, mode=mode) as client:
        tools = await client.list_tools()
        result = await client.call_tool(
            "orders_cancel_order",
            {"order_id": 4821, "reason": "customer changed their mind"})
    lines = [l.split(" ", 2) for l in open(log, encoding="utf-8")]
    return [(l[1], json.loads(l[2]), len(l[2].encode())) for l in lines], \
        len(tools.tools), result

def label(msg, asked):
    if "method" in msg:
        return msg["method"]
    return asked.get(msg["id"], "?") + " ka result"

SESSIONS = {}
for mode in ("legacy", "auto", "2026-07-28"):
    SESSIONS[mode] = asyncio.run(session(mode))
    wire, n_tools, result = SESSIONS[mode]
    asked = {m["id"]: m["method"] for _, m, _ in wire if "method" in m
             and "id" in m}
    print(f"mode={mode}: {len(wire)} messages, listed {n_tools} "
          "tools")
    for i, (arrow, msg, size) in enumerate(wire, 1):
        print(f"  {i}  {'->' if arrow == '>' else '<-'}  "
              f"{pad(label(msg, asked), 34)}{size:>8,} bytes")
```

```text
mode=legacy: 7 messages, listed 96 tools
  1  ->  initialize                             153 bytes
  2  <-  initialize ka result                   251 bytes
  3  ->  notifications/initialized               55 bytes
  4  ->  tools/list                              47 bytes
  5  <-  tools/list ka result                39,468 bytes
  6  ->  tools/call                             147 bytes
  7  <-  tools/call ka result                    128 bytes
mode=auto: 6 messages, listed 96 tools
  1  ->  server/discover                        246 bytes
  2  <-  server/discover ka result              342 bytes
  3  ->  tools/list                             241 bytes
  4  <-  tools/list ka result                39,612 bytes
  5  ->  tools/call                             330 bytes
  6  <-  tools/call ka result                   239 bytes
mode=2026-07-28: 4 messages, listed 96 tools
  1  ->  tools/list                             241 bytes
  2  <-  tools/list ka result                39,612 bytes
  3  ->  tools/call                             330 bytes
  4  <-  tools/call ka result                   239 bytes
```

Note: yeh output original (Chinese-run) experiment se hai; sample reason string Latin mein badla gayi - isliye byte counts original run ke hain, Hindi-string run ke nahi।

Teeno modes ne same 96 tools list kiye, call bhi safal - farq messages mein:

- **legacy** handshake-era flow: pehle `initialize` (153 B), result (251 B), phir `notifications/initialized` (55 B) - handshake khud 3 messages, 459 bytes, tabhi `tools/list` shuru;
- **2026-07-28** seedha `tools/list` - total 4 messages; keemat: har request `_meta` le jaati hai, isliye `tools/list` request 47 se 241 bytes, `tools/call` 147 se 330 bytes;
- **auto** pehle `server/discover` probe (246 B request, 342 B response), server ke 2026-07-28 support confirm karne ke baad naya protocol - direct version se 2 messages zyada, purane servers ke saath compatibility ke badle।

नीचे का कंपोनेंट इस वायर लॉग को क़दम-दर-क़दम रीप्ले बनाता है: कनेक्शन मोड चुनें और पिछला/अगला से कॉल चलें, हर संदेश की दिशा, बाइट और भूमिका देखें——और कौन सा एक संदेश ट्रैफ़िक हावी करता है।

Total bytes gino to protocol overhead tool list ke saamne chhota hai:

```python
for mode, (wire, n_tools, result) in SESSIONS.items():
    up = sum(s for a, _, s in wire if a == ">")
    down = sum(s for a, _, s in wire if a == "<")
    big = max(s for _, _, s in wire)
    print(f"{mode:<11} sent {up:>5,} B recv {down:>6,} B "
          f"ex-largest {up + down - big:>5,} B")
print(f"tools/list response: {big:,} bytes, "
      f"{big / len(rows):.0f} bytes / tool")
```

```text
legacy      sent   402 B recv 39,847 B ex-largest   781 B
auto        sent   817 B recv 40,193 B ex-largest 1,398 B
2026-07-28  sent   571 B recv 39,851 B ex-largest   810 B
tools/list response: 39,612 bytes, 413 bytes / tool
```

Note: numbers original run se hain; print labels Latin transliteration mein likhe gaye hain।

Dono protocols ka total traffic lagbhag same (sent+recv: legacy 40,249 bytes, 2026-07-28 40,422 bytes), jabki `tools/list` ka response akela 39,612 bytes - 2026-07-28 total ka 98%. **Stateless jo bachata hai woh round-trips aur server-side session state hai, bandwidth nahi; asli bada hissa tool definitions hai.** 96 tools ka average 413 bytes/tool - agla experiment isi ko naapta hai।

### Wire messages mein kya hai

`auto` mode ki teen representative messages print karein (lambi strings cut, response ke `serverInfo` hataye):

```python
def cut(x):
    if isinstance(x, dict):
        return {k: cut(v) for k, v in x.items()}
    if isinstance(x, list):
        return [cut(v) for v in x]
    return x[:70] + "..." if isinstance(x, str) and len(x) > 73 else x

def pretty(msg):
    """Print a message: long strings cut, the serverInfo stamp dropped."""
    msg = json.loads(json.dumps(msg))
    msg.get("result", {}).pop("_meta", None)
    print(json.dumps(cut(msg), indent=1, ensure_ascii=False))

wire = SESSIONS["auto"][0]
print("# server/discover ka response")
pretty(wire[1][1])
print("# tools/call ka request")
pretty(wire[4][1])
print("# tools/call ka response")
pretty(wire[5][1])
```

```text
# server/discover ka response
{
 "jsonrpc": "2.0",
 "id": 1,
 "result": {
  "cacheScope": "private",
  "capabilities": {
   "prompts": {
    "listChanged": true
   },
   "resources": {
    "listChanged": true,
    "subscribe": true
   },
   "tools": {
    "listChanged": true
   }
  },
  "resultType": "complete",
  "supportedVersions": [
   "2026-07-28"
  ],
  "ttlMs": 0
 }
}
# tools/call ka request
{
 "jsonrpc": "2.0",
 "id": 3,
 "method": "tools/call",
 "params": {
  "name": "orders_cancel_order",
  "arguments": {
   "order_id": 4821,
   "reason": "customer changed their mind"
  },
  "_meta": {
   "io.modelcontextprotocol/protocolVersion": "2026-07-28",
   "io.modelcontextprotocol/clientInfo": {
    "name": "mcp",
    "version": "0.1.0"
   },
   "io.modelcontextprotocol/clientCapabilities": {}
  }
 }
}
# tools/call ka response
{
 "jsonrpc": "2.0",
 "id": 3,
 "result": {
  "content": [
   {
    "text": "ok",
    "type": "text"
   }
  ],
  "isError": false,
  "resultType": "complete",
  "structuredContent": {
   "result": "ok"
  }
 }
}
```

Dhyan dene layak baatein:

- Har request ke `params._meta` mein teen cheezein: `io.modelcontextprotocol/protocolVersion`, `io.modelcontextprotocol/clientInfo`, `io.modelcontextprotocol/clientCapabilities`. Handshake nahi - server inhi se har request samajhta hai; isliye protocol level par sticky session ki zaroorat nahi, koi bhi server instance koi bhi request handle kar sakta hai (cross-request state chahiye to server khud state handles bheje - security section dekhein);
- `server/discover` ka response `supportedVersions` aur `capabilities` batata hai (yeh server tools, resources, prompts support karta hai, list-change notifications bhi); `ttlMs` aur `cacheScope` cache hints - SDK default `ttlMs: 0`, literally "turant expire"; client se tool list cache karwana ho to server khud set kare;
- Har response mein `resultType: "complete"` - 2026-07-28 se required: `"complete"` = normal result; `"input_required"` = server ko continue karne ke liye zyada input chahiye (multi-turn round-trip requests - purane server-initiated requests ka replacement);
- Tool result do forms mein: `content` model ke liye text; `structuredContent` wahi result structured (kyunki tool ne output schema declare kiya)।

### Handshake nahi, SDK nahi - seedha protocol

SDK message details chhupa deta hai. Neeche wala `Raw` class server child process ko seedha JSON lines likhta hai; saat cases stateless protocol ke behaviour aur do error types dono dikhate hain:

```python
class Raw:
    """Speak the protocol by hand: no SDK on the client side."""

    META = {"io.modelcontextprotocol/protocolVersion": "2026-07-28",
            "io.modelcontextprotocol/clientCapabilities": {}}

    def __init__(self):
        self.n = 0
        self.proc = subprocess.Popen(
            [PY, os.path.join(WORK, "server.py"),
             os.path.join(WORK, "catalog.txt")], text=True,
            stdin=subprocess.PIPE, stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)

    def call(self, method, params=None, meta=True):
        self.n += 1
        params = dict(params or {})
        if meta:
            params["_meta"] = meta if isinstance(meta, dict) else self.META
        msg = {"jsonrpc": "2.0", "id": self.n, "method": method,
               "params": params}
        self.proc.stdin.write(json.dumps(msg) + "\n")
        self.proc.stdin.flush()
        return json.loads(self.proc.stdout.readline())

    def close(self):
        self.proc.stdin.close()
        self.proc.wait(timeout=10)
        return self.proc.stderr.read()

raw, asked = Raw(), {"name": "orders_get_order"}
CASES = [
    ("pehla message hi tools/call hai",
     "tools/call",
     {**asked, "arguments": {"order_id": 4821}}, True),
    ("wahi call, par _meta ke bina", "tools/call",
     {**asked, "arguments": {"order_id": 4821}}, False),
    ("non-existent tool name", "tools/call",
     {"name": "orders_get_ordr", "arguments": {}}, True),
    ("tool ToolError phenkta hai (expected failure)",
     "tools/call",
     {**asked, "arguments": {"order_id": -1}}, True),
    ("tool internally crash (RuntimeError)",
     "tools/call",
     {**asked, "arguments": {"order_id": 0}}, True),
    ("parameter type galat", "tools/call",
     {**asked, "arguments": {"order_id": "x"}}, True),
    ("koi nahi bolne wala protocol version", "tools/call",
     {**asked, "arguments": {"order_id": 1}},
     {**Raw.META, "io.modelcontextprotocol/protocolVersion": "1999-01-01"}),
]
for title, method, params, meta in CASES:
    msg = raw.call(method, params, meta)
    print("##", title)
    pretty(msg)
```

```text
## pehla message hi tools/call hai
{
 "jsonrpc": "2.0",
 "id": 1,
 "result": {
  "content": [
   {
    "text": "ok",
    "type": "text"
   }
  ],
  "isError": false,
  "resultType": "complete",
  "structuredContent": {
   "result": "ok"
  }
 }
}
## wahi call, par _meta ke bina
{
 "jsonrpc": "2.0",
 "id": 2,
 "error": {
  "code": -32602,
  "message": "params._meta must be an object carrying the required 'io.modelcontextp..."
 }
}
## non-existent tool name
{
 "jsonrpc": "2.0",
 "id": 3,
 "result": {
  "content": [
   {
    "text": "Unknown tool: orders_get_ordr",
    "type": "text"
   }
  ],
  "isError": true,
  "resultType": "complete"
 }
}
## tool ToolError phenkta hai (expected failure)
{
 "jsonrpc": "2.0",
 "id": 4,
 "result": {
  "content": [
   {
    "text": "Error executing tool orders_get_order: order_id must be >= 0, got -1",
    "type": "text"
   }
  ],
  "isError": true,
  "resultType": "complete"
 }
}
## tool internally crash (RuntimeError)
{
 "jsonrpc": "2.0",
 "id": 5,
 "result": {
  "content": [
   {
    "text": "Error executing tool orders_get_order",
    "type": "text"
   }
  ],
  "isError": true,
  "resultType": "complete"
 }
}
## parameter type galat
{
 "jsonrpc": "2.0",
 "id": 6,
 "result": {
  "content": [
   {
    "text": "Error executing tool orders_get_order: 1 validation error for orders_g...",
    "type": "text"
   }
  ],
  "isError": true,
  "resultType": "complete"
 }
}
## koi nahi bolne wala protocol version
{
 "jsonrpc": "2.0",
 "id": 7,
 "error": {
  "code": -32022,
  "message": "Unsupported protocol version",
  "data": {
   "supported": [
    "2026-07-28"
   ],
   "requested": "1999-01-01"
  }
 }
}
```

Note: numbers original run se hain; case titles Latin transliteration mein likhe gaye hain।

Saat cases ki table:

| Situation | Server ka jawab | Class |
| --- | --- | --- |
| Pehla message hi `tools/call` | Safal, `ok` return | Bina handshake bhi kaam karta hai |
| Wahi call, `_meta` hatakar | JSON-RPC error `-32602`; `_meta` ke required fields maangta hai | Protocol error |
| Tool name misspell | Result `isError: true` ke saath, text `Unknown tool: ...` | Neeche ka note dekhein |
| Tool `ToolError` phenkta hai | `isError: true`; text mein specific reason (`order_id must be >= 0, got -1`) | Tool execution error; model isse fix kar sakta hai |
| Tool crash (`RuntimeError`) | `isError: true`; text sirf `Error executing tool orders_get_order` | Tool execution error; details hidden |
| Param type galat | `isError: true`; text validation report (`1 validation error for ...`) | Tool execution error |
| Version `1999-01-01` | JSON-RPC error `-32022`; `data` mein `supported` aur `requested` | Protocol error |

Spec tool errors do types mein batati hai: **protocol error** = request hi problem hai (unknown tool, bad format, server fault) - JSON-RPC error ke roop mein; model usually fix nahi kar sakta; spec kehta hai client "may" use model ko de. **Tool execution error** = tool runtime ka issue (API fail, validation fail, business rules) - result mein `isError: true` ke saath; spec maangti hai client "should" use model ko de, taaki model khud sudhaarkar retry kare. 2025-11-25 version aur clearly: input-validation errors tool execution errors ki tarah return hon - model self-correct kar sake।

Is experiment ki do yaad-rakha baatein:

1. **Tool crash aur tool error ka model ke liye visibility alag hai.** `ToolError` ka reason text result mein aata hai - model "order_id >= 0 hona chahiye" dekh kar sudhaar sakta hai; `RuntimeError` ke details sirf server ke stderr mein gaye (upar ke output ke end ki `Tool ...` lines); model ko sirf `Error executing tool` mila - na kya hua pata, na retry karna chahiye ya nahi. Expected failures ke liye actionable error text likhna tool design ka hissa hai;
2. **Unknown tool name SDK 2.3.0 mein tool execution error ki tarah aata hai**, jabki spec 2026-07-28 ke error examples "unknown tool" ko protocol error (`-32602`, `Unknown tool: invalid_tool_name`) maante hain. Dono representations mein model `Unknown tool` text dekhta hai, par client ko dono handle karne padte hain. Hum sirf observed behaviour report karte hain; spec-SDK ka yeh difference intentional hai ya implementation detail - verify nahi kiya।

### Tool wire par kaisa dikhta hai

```python
reply = raw.call("tools/list")["result"]
tools = reply["tools"]
print("response fields: " + ", ".join(sorted(reply)))
print(f"ttlMs: {reply['ttlMs']}, cacheScope: {reply['cacheScope']}")
print(f"tools in one page: {len(tools)}, "
      f"nextCursor: {reply.get('nextCursor')}")
print("one tool's fields: " + ", ".join(sorted(tools[0])))
json.dump(tools, open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                   "catalog.hi.json"), "w"))
tool = next(t for t in tools if t["name"] == "orders_cancel_order")
print(json.dumps(tool, indent=1, ensure_ascii=False))
stderr = raw.close().split("\n")
print("server stderr (sirf Tool se shuru hone wali lines):")
for line in [l for l in stderr if l.startswith("Tool ")]:
    print(" ", line[:78])
```

```text
response fields: _meta, cacheScope, resultType, tools, ttlMs
ttlMs: 0, cacheScope: private
tools in one page: 96, nextCursor: None
one tool's fields: description, inputSchema, name, outputSchema
{
 "description": "abhi ship nahi hue order ko cancel karna",
 "inputSchema": {
  "type": "object",
  "properties": {
   "order_id": {
    "title": "Order Id",
    "type": "integer"
   },
   "reason": {
    "title": "Reason",
    "type": "string"
   }
  },
  "required": [
   "order_id",
   "reason"
  ],
  "title": "orders_cancel_orderArguments"
 },
 "name": "orders_cancel_order",
 "outputSchema": {
  "properties": {
   "result": {
    "title": "Result",
    "type": "string"
   }
  },
  "required": [
   "result"
  ],
  "title": "orders_cancel_orderOutput",
  "type": "object"
 }
}
server stderr (sirf Tool se shuru hone wali lines):
  Tool 'orders_get_ordr' failed: 'Unknown tool: orders_get_ordr'
  Tool 'orders_get_order' failed: 'Error executing tool orders_get_order: order_
  Tool 'orders_get_order' raised an unexpected exception
  Tool 'orders_get_order' rejected arguments: ['order_id']
```

Note: numbers original run se hain; description text Hindi mein badla gaya - byte/token counts original run ke hain।

Tool wire par chaar fields: `name`, `description`, `inputSchema`, aur - function ke return annotation ki wajah se - SDK auto-generated `outputSchema`. SDK har param ko `title` bhi deta hai (`Order Id`) - JSON Schema generator ka by-product; koi info nahi, tokens khaata hai - agla experiment naapta hai. `tools/list` ka response ek poora page: 96 tools, koi `nextCursor` nahi - paging optional; yeh server ek hi baar mein sab deta hai।

### Streamable HTTP: headers aur Origin

Stdio ke alawa HTTP. 2026-07-28 har POST ko `MCP-Protocol-Version` maangti hai, aur body ke method/tool names ko `Mcp-Method`, `Mcp-Name` headers mein mirror karti hai - wajah: load balancers, gateways, observability tools body parse kiye bina route/check kar sakein. Mirror ek risk laata hai: router header se decide kare, server body se execute - mismatch policy-bypass ka darwaza. Isliye spec maangti hai server header-body consistency check kare; mismatch par HTTP 400 + `-32020` (`HeaderMismatch`)।

Doosra check `Origin`: spec maangti hai server saare connections ka `Origin` validate kare DNS-rebinding ke against; illegal Origin par 403; local server sirf 127.0.0.1 par bind kare।

```python
import http.client, shutil, socket, time

HTTP_SERVER = '''
import sys
from mcp.server import MCPServer

mcp = MCPServer("acme-backoffice")

@mcp.tool()
def orders_get_order(order_id: int) -> str:
    return "ok"

mcp.run("streamable-http", host="127.0.0.1", port=int(sys.argv[1]))
'''
open(os.path.join(WORK, "http_server.py"), "w").write(HTTP_SERVER)
with socket.socket() as s:
    s.bind(("127.0.0.1", 0))
    port = s.getsockname()[1]
proc = subprocess.Popen([PY, os.path.join(WORK, "http_server.py"), str(port)],
                        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for _ in range(100):
    try:
        socket.create_connection(("127.0.0.1", port), timeout=0.2).close()
        break
    except OSError:
        time.sleep(0.1)

def post(body, headers):
    conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10)
    conn.request("POST", "/mcp", json.dumps(body),
                 {"Content-Type": "application/json",
                  "Accept": "application/json, text/event-stream", **headers})
    reply = conn.getresponse()
    kind, data = reply.getheader("Content-Type"), reply.read().decode()
    conn.close()
    return reply.status, kind, data

call = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {
    "name": "orders_get_order", "arguments": {"order_id": 5},
    "_meta": Raw.META}}
ok = {"MCP-Protocol-Version": "2026-07-28", "Mcp-Method": "tools/call",
      "Mcp-Name": "orders_get_order"}
HTTP_CASES = [
    ("teen headers body se match", ok),
    ("Mcp-Method = tools/list, body = tools/call",
     {**ok, "Mcp-Method": "tools/list"}),
    ("Mcp-Name doosre tool ki taraf",
     {**ok, "Mcp-Name": "orders_cancel_order"}),
    ("Origin header doosri site se",
     {**ok, "Origin": "http://evil.example"}),
    ("koi MCP header nahi", {}),
]
for title, headers in HTTP_CASES:
    status, kind, data = post(call, headers)
    print("##", title)
    print("HTTP", status, kind or "(no content type)")
    try:
        msg = json.loads(data)
        if "error" in msg:
            print("error", msg["error"]["code"])
            print(" ", msg["error"]["message"])
        else:
            print("result:", msg["result"]["content"][0]["text"],
                  "| resultType:", msg["result"]["resultType"])
    except ValueError:
        print(" ", data)
proc.terminate()
proc.wait(timeout=10)
shutil.rmtree(WORK)
```

```text
## teen headers body se match
HTTP 200 application/json
result: ok | resultType: complete
## Mcp-Method = tools/list, body = tools/call
HTTP 400 application/json
error -32020
  mcp-method header does not match the request body's method
## Mcp-Name doosre tool ki taraf
HTTP 400 application/json
error -32020
  mcp-name header does not match the request body's 'name' parameter
## Origin header doosri site se
HTTP 403 (no content type)
  Invalid Origin header
## koi MCP header nahi
HTTP 400 application/json
error -32600
  Bad Request: Missing session ID
```

Paanch cases ka result spec se match: teen headers body se match - 200; `Mcp-Method`/`Mcp-Name` body se alag - 400 + `-32020`; doosri site ka `Origin` - 403. Aakhri case mein koi MCP header nahi - SDK ne `Missing session ID` diya: SDK ka server dono zamane serve karta hai; version-header-wali request ko handshake-era request samjha, aur usko session ID chahiye. SDK compatibility behaviour hai; spec 2026-07-28 khud mein session nahi hai।

## Security boundaries

Protocol sirf mechanism deta hai; security host, client, server teeno ke apne-apne kaam se aati hai. Official [security best practices](https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices) aur [authorization spec](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization) ke aam problems ek table mein:

| Problem | Kaise hota hai | Spec ka ilaj |
| --- | --- | --- |
| Local server compromised ya malicious | One-click install config mein hidden malicious start command, ya server khud malicious payload; machine par chhoda HTTP server DNS rebinding se exploit | One-click clients pehle poora command dikhakar consent lein; dangerous patterns warn; sandbox + least privilege; local servers ke liye stdio prefer |
| Token passthrough | Server client ka laaya - apne liye issue na hua - token seedha downstream API ko de de | Server koi bhi clearly-apne-naam-issued token accept na kare; token audience validate kare |
| Confused deputy | Proxy server third-party authorization server ke liye static client ID + dynamic registration; existing consent cookies se authorization code cheenna | Proxy servers har client ke liye alag user consent lein, phir forward karein |
| SSRF | Malicious server OAuth metadata mein intranet/cloud-metadata address bhar kar client ko request karwata hai | Client OAuth-related URLs validate aur restrict kare (production HTTPS enforce waghera) |
| State-handle hijack | Stateless protocol mein cross-request state wale servers khud handles dete hain (cart ID waghera); attacker doosre ka handle guess/kar le | Handle possession = authentication na samjho; secure randomness se generate, authenticated user se bind |
| Over-privileged tokens | Ek hi baar `files:*`, `admin:*` jaise broad scopes; leak par blast radius bada | Least privilege: shuru mein low-risk scopes; privileged operations par `WWW-Authenticate` scope ke through step-up |

Authorization khud optional hai (authorization is OPTIONAL). Zaroorat par spec ka tareeka: protected MCP server = OAuth 2.1 resource server; protected-resource metadata (RFC 9728) se client ko authorization server batata hai; client ko resource indicators (RFC 8707) implement karne chahiye - token sirf isi server ke liye; client registration preferably Client ID Metadata Documents; dynamic client registration (DCR) ko 2026-07-28 mein deprecated; insufficient scope par 403 + `insufficient_scope`, client usi se step-up kare. stdio servers is sab se bahar - spec environment variables se credentials lene ko kehta hai।

Ek problem protocol ke bahar hai: **tool descriptions aur results model context mein jaane wale text hain**. Malicious/compromised server instructions descriptions ya results mein chhupa sakta hai - prompt injection ka ek entry point ([prompt injection aur jailbreaks](https://dmxsf.com/hi/wiki/safety/prompt-injection-and-jailbreaks/) dekhein). Spec ka stance: client sensitive operations se pehle user confirm kare, tool inputs user ko dikhaye (data exfiltration rokne ke liye), tool results model ko dene se pehle validate kare; protocol khud judge nahi karega।

## Experiment 2: definitions kitne tokens leti hain, model phir bhi sahi chunta hai?

Experiment 1 ne dikhaya ki tool list hi lagbhag poora traffic hai. Yeh experiment wahi 96 definitions model ke saamne rakhta hai aur do sawaal poochhta hai: kitne tokens; aur poore definitions dekhne par model tools sahi chunta hai ya nahi. Saath mein do cheaper approaches: BM25 retrieval, aur per-tool-one-line index phir selected tool ki full definition dekhna।

### Design: ek catalog, 24 requests, teen approaches

- **Catalog** = experiment 1 ke 96 tools, JSON file mein export - definitions exactly wahi jo server `tools/list` mein bhejta hai।
- **Model** Qwen3-4B (Apache-2.0), MPS backend, float32, thinking off, greedy decoding. Definitions chat template ke `tools` param se prompt mein jaati hain - isliye token counts Qwen3 tokenizer ke; template/tokenizer badla to numbers badlenge।
- **Requests**: 8 target tools x 3 phrasings = 24. Phrasings param values dete hain (order number, address, phone) par tool name nahi; kuch phrasings description ke words use karti hain ("cancel"), kuch synonyms ("revoke", "delete", "send back"). Target tools ke paas near-neighbours hain: `orders_cancel_order` 7 doosre tools ke saath verb `cancel` share karta hai; `shipping_update_ship_address` 7 ke saath `update`।
- **Grading**: reply ek tool call hai, naam sahi, aur saare key param values included - `ok`; warna `wrong_tool`, `wrong_arg`, ya `no_call`/`bad_json`. Keyword grading hai - dono directions mein galti (value galat field mein ho to bhi pass) - isliye failure analysis replies padhti hai।
- **Teen approaches.** *Full-context*: 8 targets + random others - total 8/24/48/96, random order, 3 seeds (seed tool set aur order tay karta hai). *BM25 top-5*: [RAG page](https://dmxsf.com/hi/wiki/applications/rag/) wala BM25 - har tool ke name, description, param names par score; best paanch prompt mein. *Index-then-inspect*: prompt mein har tool ki ek line (name, params, description); model sirf ek tool naam answer kare; doosre prompt mein sirf us tool ki full definition; phir call issue karwao।

> [!NOTE] Experiment environment
> Neeche ke code blocks order se poora script banate hain. Environment: Apple M2 Max (64 GB), PyTorch MPS backend, float32; Python 3.14.3, PyTorch 2.10.0, transformers 5.3.0 (`setup` print karta hai). Page Qwen3-4B ka full run dikhata hai. Do chhote models Qwen2.5-1.5B-Instruct aur Qwen2.5-0.5B-Instruct (dono Apache-2.0) same script, sirf `MODEL` env var badalkar chalaye; unke numbers sirf summary tables mein. Greedy decoding se replies isi machine par deterministic; doosri machine par floating-point farq se kuch replies alag ho sakte hain. 4B ka run lagbhag 37 minutes. Page par wahi run hai jo pehli baar khaali stderr ke saath poora chala. Timings sirf is laptop ke float32 ke liye - sirf ratios dekho।

### Code: definitions prompt mein kaise jaati hain

`setup` model load karta hai. `tools` catalog padh kar chat template se prompt render karta hai: `spec` catalog ki entry ko template ke function format mein badalta hai (`title` field - SDK schema generator ka - hatane ka option ke saath), `render` tools + request se poora prompt banata hai, `split` user-turn se pehle prompt kaat-ta hai: aadha hissa sirf tools par nirbhar - ek baar compute karke prefix cache ki tarah reuse।

```python
import json, math, os, platform, random, re, textwrap, time, unicodedata
import torch, transformers
from transformers import AutoModelForCausalLM, AutoTokenizer, DynamicCache
from transformers import logging as hf_logging

hf_logging.set_verbosity_error()
hf_logging.disable_progress_bar()
MODEL = os.environ.get("MODEL", "Qwen/Qwen3-4B")
DEV = "mps"
tok = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32)
model = model.to(DEV).eval()
STOP = {tok.convert_tokens_to_ids("<|im_end|>"), tok.eos_token_id}
n_par = sum(p.numel() for p in model.parameters())
print("python", platform.python_version(), "| torch", torch.__version__,
      "| transformers", transformers.__version__)
print(MODEL, f"| {n_par / 1e9:.2f}B parameters | float32 on", DEV)

def wid(s):
    return sum(2 if unicodedata.east_asian_width(c) in "WF" else 1 for c in s)

def row(cells, widths):
    """First cell left-aligned, the rest right-aligned (wide chars count 2)."""
    out = [cells[0] + " " * (widths[0] - wid(cells[0]))]
    out += [" " * (w - wid(c)) + c for c, w in zip(cells[1:], widths[1:])]
    return "  ".join(out)
```

```text
python 3.14.3 | torch 2.10.0 | transformers 5.3.0
Qwen/Qwen3-4B | 4.02B parameters | float32 on mps
```

```python
HERE = os.path.dirname(os.path.abspath(__file__))
LIST = json.load(open(os.path.join(HERE, "catalog.hi.json")))
TOOLS = {t["name"]: t for t in LIST}
NAMES = list(TOOLS)
SYSTEM = "Tum Acme ka backoffice bot ho. Request complete karne ke liye ek tool call karo।"

def strip_titles(x):
    """Drop the generated "title" strings of a JSON Schema."""
    if isinstance(x, dict):
        return {k: strip_titles(v) for k, v in x.items()
                if not (k == "title" and isinstance(v, str))}
    return x

def spec(name, titles=True):
    t = TOOLS[name]
    schema = t["inputSchema"] if titles else strip_titles(t["inputSchema"])
    return {"type": "function", "function": {
        "name": name, "description": t["description"], "parameters": schema}}

def render(names, query, titles=True):
    msgs = [{"role": "system", "content": SYSTEM},
            {"role": "user", "content": query}]
    return tok.apply_chat_template(
        msgs, tools=[spec(n, titles) for n in names], tokenize=False,
        add_generation_prompt=True, enable_thinking=False)

def n_tokens(text):
    return len(tok(text, add_special_tokens=False).input_ids)

def split(names, query):
    """Cut the prompt before the user turn: the front part is shared."""
    full = render(names, query)
    cut = full.rindex("<|im_start|>user")
    return full[:cut], full[cut:]

BASE = n_tokens(render([], "x"))
ALL = n_tokens(render(NAMES, "x"))
PLAIN = n_tokens(render(NAMES, "x", titles=False))
print("tools in catalog:", len(NAMES))
print("prompt without tools:", BASE, "tokens")
print(f"prompt with all {len(NAMES)} tools:",
      f"{ALL:,} tokens;",
      f"without title fields {PLAIN:,}")
print("---- one-tool prompt (wrapped) ----")
for line in render(NAMES[:1], "x").split("\n"):
    print("\n".join(textwrap.wrap(line, 84)) or "")
```

```text
tools in catalog: 96
prompt without tools: 33 tokens
prompt with all 96 tools: 8,057 tokens; without title fields 6,325
---- one-tool prompt (wrapped) ----
<|im_start|>system
Tum Acme ka backoffice bot ho. Request complete karne ke liye ek tool call karo।

# Tools

You may call one or more functions to assist with the user query.

You are provided with function signatures within <tools></tools> XML tags:
<tools>
{"type": "function", "function": {"name": "orders_get_order", "description":
"order ka status, items aur amount poochho", "parameters": {"type": "object", "properties": {"order_id":
{"title": "Order Id", "type": "integer"}}, "required": ["order_id"], "title":
"orders_get_orderArguments"}}}
</tools>

For each function call, return a json object with function name and arguments within
<tool_call></tool_call> XML tags:
<tool_call>
{"name": <function-name>, "arguments": <args-json-object>}
</tool_call><|im_end|>
<|im_start|>user
x<|im_end|>
<|im_start|>assistant
<think>

</think>
```

Note: yeh output original (Chinese-run) experiment se hai; system text Hindi mein badla gaya - token counts original run ke hain।

Output ki teen baatein:

- Tools nahi: prompt 33 tokens - system prompt + template skeleton।
- Saare 96 definitions: 8,057 tokens - average 84/tool. Upar ka single-tool prompt wajah dikhata hai: har definition ek JSON line; schema server se aaya sab rakhta hai।
- Unmein 1,732 tokens (21%) `title` fields hain (`"title": "Order Id"`, `"title": "orders_get_orderArguments"`): Python function signatures se schema generation ka by-product; descriptions/param names ko kuch nahi jodta. Accuracy experiment inhe rakhta hai (server jaise bhejta hai waise); hatane par accuracy badalti hai ya nahi - naapa nahi; aur hatana server-side change hai।

### Code: requests aur runner

`probes` 24 requests define karta hai: har target tool ke liye correct call ke zaroori param values (`keys`) aur teen phrasings; saath mein kitne tools target ke saath verb share karte hain. `model` runner hai: `prefill` shared prefix ka KV cache 1,024-token chunks mein banata hai; `decode` cache se greedy continue karta hai jab tak model `</tool_call>` na likh de; phir cache prefix tak crop - agli request reuse kare; `verdict` reply ko score karta hai. Aakhri lines do tools se ek request - smoke test।

<details>
<summary>Expand: 24 requests aur unke near-neighbours</summary>

```python
PROBES = [
    ("orders_cancel_order", ["4821"], [
        "Order 4821 abhi ship nahi hua; customer cancel karna chahta hai।",
        "Order 4821 cancel karo; reason duplicate order hai।",
        "Customer order 4821 revoke karna chahta hai।"]),
    ("shipping_update_ship_address", ["Rue Cler"], [
        "Package 1Z999AA10123456784 in transit; ise Rue Cler 12 par bhejo।",
        "Waybill 7700112233 abhi pahuncha nahi; ise Rue Cler 12 par bhej do।",
        "In-transit package CX0099 ko Rue Cler 12 par divert karo।"]),
    ("hr_update_employee_phone", ["311", "5550123"], [
        "Employee 311 ka phone badla; naya number +49 30 5550123 hai।",
        "Employee 311 ka phone +49 30 5550123 kar do।",
        "HR record mein employee 311 ka number +49 30 5550123 update karna hai।"]),
    ("calendar_cancel_event", ["ev-2207"], [
        "Event ev-2207 cancel karo; meeting postpone ho gayi hai।",
        "Calendar mein ev-2207 nahi hoga; yeh activity delete kar do।",
        "Activity ev-2207 revoke kar do kripa karke।"]),
    ("billing_issue_refund", ["pay_7781", "25"], [
        "Payment pay_7781 ka 25 customer ke card par wapas bhejo।",
        "Payment pay_7781 ka refund 25 do।",
        "Customer ne complaint ki; pay_7781 ke 25 wapas bhej do।"]),
    ("docs_share_doc", ["d-310", "ana@acme.io"], [
        "Document d-310 ko ana@acme.io ke saath share karo।",
        "ana@acme.io ko document d-310 dikhne do।",
        "ana@acme.io ko document d-310 ka access de do।"]),
    ("analytics_cancel_report_schedule", ["sch-12"], [
        "Scheduled job sch-12 rok do; weekly report ab nahi chahiye।",
        "Report schedule sch-12 cancel karo।",
        "Report scheduling sch-12 ki zaroorat nahi hai।"]),
    ("crm_merge_contacts", ["118", "342"], [
        "Contacts 118 aur 342 ek hi insaan hain; 118 ko 342 mein merge karo।",
        "Duplicate contacts merge karo: 118 ko 342 mein।",
        "CRM mein 118 aur 342 duplicate hain; merge kar do।"]),
]
QUERIES = [(t, keys, q) for t, keys, qs in PROBES for q in qs]
TARGETS = [p[0] for p in PROBES]
print(len(PROBES), "target tools x 3 phrasings each =",
      len(QUERIES), "requests")
for tool in TARGETS:
    verb = tool.split("_")[1]
    kin = [n for n in NAMES if n.split("_")[1] == verb]
    print(f"  {tool:<34} {len(kin)} tools share verb",
          f"({verb})")
```

```text
8 target tools x 3 phrasings each = 24 requests
  orders_cancel_order                7 tools share verb (cancel)
  shipping_update_ship_address       7 tools share verb (update)
  hr_update_employee_phone           7 tools share verb (update)
  calendar_cancel_event              7 tools share verb (cancel)
  billing_issue_refund               1 tools share verb (issue)
  docs_share_doc                     2 tools share verb (share)
  analytics_cancel_report_schedule   7 tools share verb (cancel)
  crm_merge_contacts                 1 tools share verb (merge)
```

</details>

```python
@torch.no_grad()
def prefill(ids, chunk=1024):
    cache = DynamicCache()
    for i in range(0, ids.shape[1], chunk):
        model(input_ids=ids[:, i:i + chunk], past_key_values=cache,
              use_cache=True)
    return cache

@torch.no_grad()
def decode(cache, ids, limit=120, until="</tool_call>"):
    """Greedy continuation of a cached prefix; the cache is cut back."""
    keep, new = cache.get_seq_length(), []
    out = model(input_ids=ids, past_key_values=cache, use_cache=True)
    assert torch.isfinite(out.logits[0, -1]).all()
    for _ in range(limit):
        nxt = int(out.logits[0, -1].argmax())
        if nxt in STOP:
            break
        new.append(nxt)
        if until in tok.decode(new):
            break
        step = torch.tensor([[nxt]], device=DEV)
        out = model(input_ids=step, past_key_values=cache, use_cache=True)
    cache.crop(keep)
    torch.mps.empty_cache()
    return tok.decode(new), len(new)

def to_ids(text):
    return tok(text, add_special_tokens=False,
               return_tensors="pt").input_ids.to(DEV)

def start(names):
    """Prefill the part of the prompt that does not depend on the request."""
    prefix = split(names, "")[0]
    ids = to_ids(prefix)
    return prefill(ids), prefix, ids.shape[1]

def ask(cache, prefix, names, query):
    full = render(names, query)
    assert full.startswith(prefix)
    return decode(cache, to_ids(full[len(prefix):]))

def verdict(text, tool, keys):
    m = re.search(r"<tool_call>\s*(\{.*\})\s*</tool_call>", text, re.S)
    if not m:
        return "no_call"
    try:
        call = json.loads(m.group(1))
        args = " ".join(str(v) for v in call.get("arguments", {}).values())
    except (ValueError, AttributeError):
        return "bad_json"
    if call.get("name") != tool:
        return "wrong_tool"
    return "ok" if all(k in args for k in keys) else "wrong_arg"

duo = ["orders_cancel_order", "orders_get_order"]
cache, prefix, n_prefix = start(duo)
text, n_new = ask(cache, prefix, duo, QUERIES[0][2])
print(repr(text), "|", n_new, "new tokens")
print("verdict:", verdict(text, QUERIES[0][0], QUERIES[0][1]))
del cache
torch.mps.empty_cache()
```

```text
'<tool_call>\n{"name": "orders_cancel_order", "arguments": {"order_id": 4821, "reason": "customer wants to cancel"}}\n</tool_call>' | 32 new tokens
verdict: ok
```

Note: yeh output original (Chinese-run) experiment se hai; model ke generated text Hindi mein badle gaye, counts wahi hain।

Smoke test reply ka shape dikhata hai: ek `<tool_call>` block, andar tool name + params wala JSON. Is baar model ne 32 new tokens; poore run ki longest reply `cost` block ke output mein।

### Code: teen selection approaches

Pehle BM25. Iski recall kisi bhi retrieval step ki ceiling hai: sahi tool top-5 mein nahi to model ke paas choose karne ka mauka hi nahi. `terms` Latin words ko whole-word tod-ta hai, Devanagari/CJK characters ko paas ke do-char bigrams (Hindi catalog ke liye); index har tool ke name (underscore = space), description aur param names par banta hai।

```python
def terms(s):
    s = s.lower()
    out = re.findall(r"[a-z][a-z0-9]*", s)
    for run in re.findall(r"[\u0900-\u097f\u4e00-\u9fff]+", s):
        out += [run[i:i + 2] for i in range(len(run) - 1)] or [run]
    return out

class BM25:
    def __init__(self, names, k1=1.5, b=0.75):
        self.names, self.k1, self.b = names, k1, b
        self.docs = []
        for n in names:
            t = TOOLS[n]
            params = " ".join(t["inputSchema"].get("properties", {}))
            doc = n.replace("_", " ") + " " + t["description"] + " " + params
            self.docs.append(terms(doc))
        self.avg = sum(map(len, self.docs)) / len(self.docs)
        df = {}
        for d in self.docs:
            for w in set(d):
                df[w] = df.get(w, 0) + 1
        N = len(self.docs)
        self.idf = {w: math.log(1 + (N - c + 0.5) / (c + 0.5))
                    for w, c in df.items()}

    def top(self, query, k):
        q, scores = set(terms(query)), []
        for d in self.docs:
            s = 0.0
            for w in q:
                f = d.count(w)
                if f:
                    norm = 1 - self.b + self.b * len(d) / self.avg
                    s += self.idf[w] * f * (self.k1 + 1) / (f + self.k1 * norm)
            scores.append(s)
        order = sorted(range(len(scores)), key=lambda i: -scores[i])
        return [self.names[i] for i in order[:k]]

bm = BM25(NAMES)
for k in (1, 3, 5, 10):
    hit = sum(t in bm.top(q, k) for t, _, q in QUERIES)
    print(f"BM25 top-{k:<2} contains correct tool:"
          f"{hit} / {len(QUERIES)}")
for t, _, q in QUERIES:
    if t not in bm.top(q, 5):
        print(f"  top 5 mein nahi: {q}")
```

```text
BM25 top-1  contains correct tool: 14 / 24
BM25 top-3  contains correct tool: 16 / 24
BM25 top-5  contains correct tool: 18 / 24
BM25 top-10 contains correct tool: 20 / 24
  top 5 mein nahi: Calendar mein ev-2207 nahi hoga; yeh activity delete kar do।
  top 5 mein nahi: Activity ev-2207 revoke kar do kripa karke।
  top 5 mein nahi: Payment pay_7781 ka 25 customer ke card par wapas bhejo।
  top 5 mein nahi: Payment pay_7781 ka refund 25 do।
  top 5 mein nahi: ana@acme.io ko document d-310 dikhne do।
  top 5 mein nahi: ana@acme.io ko document d-310 ka access de do।
```

Note: numbers original (Chinese-run) experiment se hain; queries Hindi mein badli gayi - yeh sirf method dikhata hai।

Phir main loop. Har seed x har tool count par `pick` tool set banata hai (8 targets zaroor; baaki random; shuffle), `start` request-independent prompt hissa prefill karta hai; 24 requests isi cache se answer hoti hain. `retrieve` block BM25 ke liye wahi karta hai: har request ke paanch tools alag - har request apna chhota prompt prefill karti hai. `index` block do steps mein।

```python
SEEDS, SIZES = (0, 1, 2), (8, 24, 48, 96)
RUNS = []

def pick(n, seed):
    """n tools: the 8 targets plus random others, in a random order."""
    others = [x for x in NAMES if x not in TARGETS]
    random.Random(f"pool-{seed}").shuffle(others)
    names = TARGETS + others[:n - len(TARGETS)]
    random.Random(f"order-{seed}-{n}").shuffle(names)
    return names

def log(cond, seed, n, qi, v, text, new, **more):
    tool = QUERIES[qi][0]
    RUNS.append(dict(cond=cond, seed=seed, n=n, qi=qi, tool=tool, v=v,
                     text=text, new=new, **more))

for seed in SEEDS:
    for n in SIZES:
        names = pick(n, seed)
        t0 = time.time()
        cache, prefix, n_prefix = start(names)
        t_pre = time.time() - t0
        t0, ok = time.time(), 0
        for qi, (tool, keys, q) in enumerate(QUERIES):
            t1 = time.time()
            text, new = ask(cache, prefix, names, q)
            v = verdict(text, tool, keys)
            ok += v == "ok"
            log("all", seed, n, qi, v, text, new, pos=names.index(tool),
                tokens=n_prefix, prefill_s=t_pre, sec=time.time() - t1)
        del cache
        torch.mps.empty_cache()
        print(f"seed {seed} n={n:<3} {n_prefix:>6,} "
              f"tokens, prefill {t_pre:>5.1f} s | "
              f"{len(QUERIES)} requests "
              f"{time.time() - t0:>5.1f} s | ok {ok}/{len(QUERIES)}")
```

```text
seed 0 n=8        815 tokens, prefill   0.4 s | 24 requests  71.9 s | ok 24/24
seed 0 n=24     2,174 tokens, prefill   3.5 s | 24 requests 106.6 s | ok 24/24
seed 0 n=48     4,075 tokens, prefill   6.6 s | 24 requests 179.1 s | ok 24/24
seed 0 n=96     8,044 tokens, prefill  18.3 s | 24 requests 253.8 s | ok 24/24
seed 1 n=8        815 tokens, prefill   0.4 s | 24 requests  66.7 s | ok 24/24
seed 1 n=24     2,151 tokens, prefill   3.2 s | 24 requests  99.1 s | ok 23/24
seed 1 n=48     4,062 tokens, prefill   6.2 s | 24 requests 181.5 s | ok 24/24
seed 1 n=96     8,044 tokens, prefill  17.1 s | 24 requests 240.0 s | ok 23/24
seed 2 n=8        815 tokens, prefill   0.5 s | 24 requests  67.1 s | ok 24/24
seed 2 n=24     2,200 tokens, prefill   3.3 s | 24 requests 100.3 s | ok 24/24
seed 2 n=48     4,193 tokens, prefill   7.3 s | 24 requests 172.8 s | ok 24/24
seed 2 n=96     8,044 tokens, prefill  17.1 s | 24 requests 236.3 s | ok 24/24
```

```python
for qi, (tool, keys, q) in enumerate(QUERIES):
    names = bm.top(q, 5)
    t1 = time.time()
    cache, prefix, n_prefix = start(names)
    text, new = ask(cache, prefix, names, q)
    log("bm25", 0, 5, qi, verdict(text, tool, keys), text, new,
        pos=names.index(tool) if tool in names else -1,
        tokens=n_tokens(render(names, q)), sec=time.time() - t1)
    del cache
    torch.mps.empty_cache()
r = [x for x in RUNS if x["cond"] == "bm25"]
print("BM25 top 5, phir model: ok",
      sum(x["v"] == "ok" for x in r), "/", len(r),
      "; correct tool paanchon mein nahi:",
      sum(x["pos"] < 0 for x in r))
```

```text
BM25 top 5, phir model: ok 18 / 24 ; correct tool paanchon mein nahi: 6
```

```python
ASK = "Sirf sabse fit tool ka naam answer karo; kuch aur mat likho।"
HEAD = "Available tools (name, params, description):"

def index_prompt(names, query):
    lines = []
    for n in names:
        params = ", ".join(TOOLS[n]["inputSchema"].get("properties", {}))
        lines.append(f"- {n}({params}): {TOOLS[n]['description']}")
    msgs = [{"role": "system",
             "content": SYSTEM + "\n\n" + HEAD + "\n" + "\n".join(lines)},
            {"role": "user", "content": query + "\n\n" + ASK}]
    return tok.apply_chat_template(msgs, tokenize=False,
                                   add_generation_prompt=True,
                                   enable_thinking=False)

for seed in SEEDS:
    names = pick(96, seed)
    full = index_prompt(names, "")
    prefix = full[:full.rindex("<|im_start|>user")]
    pid = to_ids(prefix)
    cache, ok = prefill(pid), 0
    for qi, (tool, keys, q) in enumerate(QUERIES):
        t1 = time.time()
        text, n1 = decode(cache, to_ids(index_prompt(names, q)[len(prefix):]),
                          limit=40, until="\n")
        found = re.findall(r"[a-z]+(?:_[a-z]+)+", text)
        chosen = found[0] if found and found[0] in TOOLS else None
        text2, n2, tokens2, v = "", 0, 0, "no_call"
        if chosen:
            c2, p2, tokens2 = start([chosen])
            text2, n2 = ask(c2, p2, [chosen], q)
            v = verdict(text2, tool, keys)
            del c2
        ok += v == "ok"
        log("index", seed, 96, qi, v, text.strip() + " | " + text2, n1 + n2,
            chosen=chosen, pos=names.index(tool), tokens=pid.shape[1],
            tokens2=tokens2, sec=time.time() - t1)
        torch.mps.empty_cache()
    del cache
    print(f"seed {seed} 96-tool index "
          f"{pid.shape[1]:>6,} tokens | ok {ok}/{len(QUERIES)}")
```

```text
seed 0 96-tool index   1,551 tokens | ok 23/24
seed 1 96-tool index   1,551 tokens | ok 20/24
seed 2 96-tool index   1,551 tokens | ok 21/24
```

## Results: 96 tools kitne kharch karte hain, kya milta hai

### Cost: tokens aur seconds

`cost` results ek table mein: prompt tokens, per-tool share, prefill time (har tool-set ek baar - prefix baad mein cached), prefix-cache-hit wali per-request time, aur 32,768-token window ka hissa:

```python
W = [10, 8, 10, 11, 11, 9]
print(row(["tools", "tokens", "per tool",
           "prefill s", "per-req s",
           "of 32k"], W))
COST = {}
for n in SIZES:
    r = [x for x in RUNS if x["cond"] == "all" and x["n"] == n]
    tokens = {x["seed"]: x["tokens"] for x in r}
    prefill_s = {x["seed"]: x["prefill_s"] for x in r}
    tok_mean = sum(tokens.values()) / len(tokens)
    COST[n] = dict(tokens=tok_mean, prefill_s=sum(prefill_s.values())
                   / len(prefill_s), sec=sum(x["sec"] for x in r) / len(r))
    print(row([str(n), f"{tok_mean:,.0f}", f"{(tok_mean - BASE) / n:.0f}",
               f"{COST[n]['prefill_s']:.1f}", f"{COST[n]['sec']:.1f}",
               f"{100 * tok_mean / 32768:.1f}%"], W))
per_tool = (COST[96]["tokens"] - BASE) / 96
for pct in (1, 5):
    limit = 32768 * pct / 100
    print(f"32,768 ka {pct}% = {limit:,.0f},"
          f" lagbhag {(limit - BASE) / per_tool:.0f} tools")
r = [x for x in RUNS if x["cond"] == "bm25"]
mean5 = sum(x["tokens"] for x in r) / len(r)
print(f"BM25 top-5: {mean5:,.0f} tokens / request, "
      f"{sum(x['sec'] for x in r) / len(r):.1f} s / request")
r = [x for x in RUNS if x["cond"] == "index"]
idx_tok = sum({x["seed"]: x["tokens"] for x in r}.values()) / len(SEEDS)
step2 = sum(x["tokens2"] for x in r) / len(r)
secs = sum(x["sec"] for x in r) / len(r)
print(f"index: {idx_tok:,.0f} tokens (cacheable)")
print(f"step two: {step2:,.0f} tokens / request, "
      f"{secs:.1f} s / request")
print("max generated tokens:",
      max(x["new"] for x in RUNS), "tokens")
```

```text
tools        tokens   per tool   prefill s   per-req s    of 32k
8                815          98          0.4          2.9       2.5%
24             2,175          89          3.3          4.2       6.6%
48             4,110          85          6.7          7.4      12.5%
96             8,044          83         17.5         10.1      24.5%
32,768 ka 1% = 328, lagbhag 4 tools
32,768 ka 5% = 1,638, lagbhag 19 tools
BM25 top-5: 544 tokens / request, 3.6 s / request
index: 1,551 tokens (cacheable)
step two: 185 tokens / request, 3.3 s / request
max generated tokens: 92 tokens
```

Note: numbers original run se hain; print labels Latin transliteration mein likhe gaye hain।

- **Tokens tools ke saath lagbhag linear.** 8 tools = 815 tokens; 96 = 8,044 - 32,768 window ka 24.5%. 48 se 96: prompt +3,934 tokens - average lagbhag 82/tool. "Per tool" column ka start zyada (8 tools par 98) kyunki chat template ka fixed instruction jo tool-list se pehle likha hai, kam tools par spread hota hai।
- **Is definition size par 1%-5% threshold jaldi aa jaata hai.** Window ka 1% = 328 tokens - lagbhag 4 tools; 5% = 1,638 - lagbhag 19 tools. Dozens-of-tools ka catalog client best practices ke "sab load karna theek hai" zone se bahar hai।
- **Prefill tokens se zyada tezi se badhta hai.** 4,110 tokens = 6.7 s; 8,044 = 17.5 s: tokens lagbhag 2x, time 2x se zyada - attention compute length ke square par badhta hai।
- **Prefix cached ho, phir bhi per-request time lagta hai.** 96 tools ka prefix cache mein: ek request 10.1 s; 8 tools 2.9 s; longest reply 92 tokens. Har generated token poora cache padhta hai; is laptop ke MPS backend par yeh padhna mehnga; server GPUs ke fused attention kernels per cached token kam dete hain - yeh ratio environment ki property hai, law nahi।
- **Do cheaper setups per-request bhi saste.** BM25 top-5: 544 tokens/prompt, 3.6 s/request - har prompt alag, shareable kuch nahi. One-line index sab requests mein shared 1,551 tokens; doosri call ek full definition ke saath (total 185 tokens); dono calls milakar 3.3 s/request।

Neeche widget is hisaab ko khud compute karne layak bana deta hai: catalog size aur har definition ke tokens drag karke dekho "sab prompt mein" window ke budget share ko kab paar karta hai; chart ke teen point is experiment ke naape hue values hain (full list 8,044, index 1,551, BM25 top-5 per request 544), accuracy ki keemat agle section mein hai।

### Accuracy: 4B model ko lagbhag kuch mehsoos nahi hota

`accuracy` conditions ke counts deta hai: `ok` = tool sahi + har key value sahi; `tool-sahi` sirf tool sahi; `wrong_tool` doosra tool; `wrong_arg` tool sahi par value missing; `no_call` usable call nahi; aakhri column per-seed `ok` counts।

```python
GROUPS = [("all", n, f"all {n}") for n in SIZES] + [
    ("bm25", 5, "BM25 top-5"), ("index", 96, "index+1")]
W = [11, 8, 9, 7, 7, 7, 9]
print(row(["cond", "ok", "tool ok",
           "wrong", "args", "no call",
           "per-seed ok"], W))
ACC = {}

def share(r, *vs):
    return sum(x["v"] in vs for x in r)

for cond, n, label in GROUPS:
    r = [x for x in RUNS if x["cond"] == cond and x["n"] == n]
    seeds = sorted({x["seed"] for x in r})
    per = [share([x for x in r if x["seed"] == s], "ok") for s in seeds]
    ACC[label] = dict(n=len(r), ok=share(r, "ok"), per=per,
                      tool=share(r, "ok", "wrong_arg"),
                      wrong=share(r, "wrong_tool"), args=share(r, "wrong_arg"),
                      none=share(r, "no_call", "bad_json"))
    a = ACC[label]
    print(row([label, f"{a['ok']}/{a['n']}", f"{a['tool']}/{a['n']}",
               str(a["wrong"]), str(a["args"]), str(a["none"]),
               "/".join(map(str, per)) if cond != "bm25" else "-"], W))
```

```text
cond             ok     tool ok      wrong     args   no call   per-seed ok
all 8           72/72      72/72        0        0        0   24/24/24
all 24          71/72      71/72        1        0        0   24/23/24
all 48          72/72      72/72        0        0        0   24/24/24
all 96          71/72      71/72        1        0        0   24/23/24
BM25 top-5      18/24      18/24        2        0        4          -
index+1         64/72      64/72        1        0        7   23/20/21
```

- **Sab prompt mein: 8/24/48/96 tools par kram se 72, 71, 72, 71 (har tier 72 mein).** Qwen3-4B har tier par lagbhag sab sahi: 24 tools par ek galat (`calendar_cancel_event` ki jagah `calendar_reschedule_event`), 96 par bhi ek (refund request `orders_return_order` ko de di)।
- **BM25 top-5: 18/24.** BM25 ne 18 requests ka sahi tool top-5 mein rakha (top-1 14, top-3 16, top-10 20); model ne 18 sab sahi kiye. BM25 ki 6 misses rephrased requests thi: "cancel" ko "nahi hoga, delete kar do", "revoke"; "refund" ko "25 wapas bhejo", "refund 25"; "share" ko "dikhne do", "access de do". Model jo nahi dikha woh nahi chun sakta: 4 baar usable call nahi, 2 baar doosra tool (`hr_cancel_leave` aur `docs_update_doc`)।
- **Index + inspect: 64/72.** Index 1,551 tokens; full list 8,044. 8 failures mein 7 `no_call`, ek `calendar_cancel_event` -> `calendar_reschedule_event`. 7 "no_call" sab refund requests: step 1 ne `billing_void_invoice` chuna, step 2 mein sirf yehi definition thi, to model text reply kar gaya. Per-reply detail neeche "read the replies" section mein।

*Figure: Teen models, greedy decoding; har point = har tool-count ke 3 random seeds (alag tool sets/orders) x 24 requests; BM25 ke liye 24; patli lines seeds ke min-max. Baen ka token count Qwen3-4B chat template se rendered prompt length; index line sirf index (step 2 mein selected tool ki full definition julti hai). Amber dotted lines 32,768-window ke 1% aur 5%. Dahina axis 0% se shuru hota hai, 0 se nahi।*

### Teen models ek saath

Table teen models ke `ok` counts saath rakhta hai. Chhote dono models same script, sirf `MODEL` env var badla: Qwen2.5-1.5B-Instruct lagbhag 11 min, Qwen2.5-0.5B-Instruct lagbhag 6 min; dono stderr khaali. Teen models ke prompts lagbhag same lambai (96 definitions: 8,057, 8,053, 8,053 tokens) - isliye token bars teeno par apply।

| Approach | Qwen3-4B | Qwen2.5-1.5B | Qwen2.5-0.5B |
| --- | ---: | ---: | ---: |
| all 8 | 72/72 (100%) | 64/72 (89%) | 46/72 (64%) |
| all 24 | 71/72 (99%) | 52/72 (72%) | 52/72 (72%) |
| all 48 | 72/72 (100%) | 49/72 (68%) | 40/72 (56%) |
| all 96 | 71/72 (99%) | 15/72 (21%) | 35/72 (49%) |
| BM25 top-5 | 18/24 (75%) | 14/24 (58%) | 16/24 (67%) |
| index+1 | 64/72 (89%) | 45/72 (62%) | 28/72 (39%) |

- **Model size tay karta hai tool-count ka nuksaan kitna.** Qwen3-4B: 8 tools 100%, 48 tools 100%, 96 tools 99%. Qwen2.5-1.5B: 8 tools 89% se girta hua 24 par 72%, 48 par 68%, 96 par sirf 21%. Qwen2.5-0.5B monotonic nahi: 8 par 64%, 24 par 72%, phir 48 par 56% aur 96 par 49%।
- **1.5B ki failures mostly "usable call nahi" hain, galat-chunna nahi.** 8 tools par 6 replies ne call nahi ki - unmein 5 `orders_cancel_order` se: uska `reason` required hai; teen phrasings mein sirf ek reason deti hai; sample reply user se reason maang raha hai ("cancel ka reason dein"). Grader ise no_call likhta hai; product mein reason maangna shayad reason invent karne se zyada safe hai - aur 4B ke smoke test ne invent kiya tha ("customer wants to cancel"). 96 tools par no-call replies 54 ho gaye - sab text-only, koi broken JSON nahi; `orders_cancel_order` aur `shipping_update_ship_address` targets ki 9 requests (3 phrasings x 3 seeds) mein ek bhi call nahi; sample ek promise-wo-call-na-karne wala reply ("Theek hai, main calendar se ev-2207 activity hata doonga।"). Target tool list ke middle third mein ho to 27 requests mein ek bhi sahi nahi (`position` section ki table)।
- **0.5B ke 8-tools par nuksaan ka alag shape: JSON toot jaata hai.** Is tier mein 21 replies mein usable call nahi; 20 broken JSON; 20 ek hi tarah se: tool name ke baad ka quote unclosed - `"name": "calendar_cancel_event,arguments": {...` - name ne baaki sab nigal liya. 24 tools par yeh fault lagbhag khatam (1 no-call). 8 se 24: `ok` 46 se 52 - par no-call replies 20 kam hue aur wrong-tool replies 5 se 19 badhe - matlab yeh improvement zyada-tar ek format-fault ke khatam hone se hai, lambi list par model ka strong hona nahi. Mujhe pata nahi chala short list yeh kyun trigger karti hai. List order ka asar bhi bada: 8 tools par per-seed ok 13 se 18 (per seed 24) - 8->24 ke average change se bhi zyada।
- **Retrieval ki ceiling recall hai; model use upar nahi le ja sakta.** BM25 top-5 mein 18/24 requests ka sahi tool tha. Qwen3-4B ne 18 sab sahi kiye; Qwen2.5-1.5B 14; Qwen2.5-0.5B 16 - paanch tools ki list bhi reliably padh le aisa nahi।
- **Index approach se model ko do steps karne aane chahiye.** Index+inspect: Qwen3-4B 89%, 1.5B 62%, 0.5B 39%. 1.5B ka step-1 kabhi catalog-se-bahar naam nahi bola (0 baar); 23 failures sab step-2: prompt mein sirf ek definition thi, phir bhi usable call nahi di. 0.5B ka step-1 20 baar catalog ka tool name nahi bola; step-2 mein bhi 3 no-calls।
- **Wrong tools mein dono chhote models ki lagbhag aadhi doosri service mein.** Neeche wali table wrong replies ko is aadhar par ginti hai ki chosen tool target ke saath same service mein hai ya nahi (`docs_share_doc` -> `docs_update_doc` same service; `billing_issue_refund` -> `orders_return_order` doosri service). Qwen3-4B ke 5 mein 2 doosri service; 1.5B aur 0.5B same-service share 54% aur 51%।

| Model | Wrong-tool replies | Same-service tool | Doosri service ka tool |
| --- | ---: | ---: | ---: |
| Qwen3-4B | 5 | 3 (60%) | 2 (40%) |
| Qwen2.5-1.5B | 26 | 14 (54%) | 12 (46%) |
| Qwen2.5-0.5B | 118 | 60 (51%) | 58 (49%) |

### Position aur failures

`position` "sab prompt mein" wali setting ke requests ko target tool ki list-position ke hisaab se teen thirds mein batata hai; `failures` wrong tools ginta hai, kuch wrong-arg replies print karta hai, teen settings ko per-target todta hai।

```python
W = [11, 8, 8, 8]
print(row(["tools", "first third",
           "middle",
           "last third"], W))
THIRDS = {}
for n in (48, 96):
    r = [x for x in RUNS if x["cond"] == "all" and x["n"] == n]
    cells = []
    for lo in range(3):
        sub = [x for x in r if x["pos"] * 3 // n == lo]
        cells.append((share(sub, "ok"), len(sub)))
    THIRDS[n] = cells
    print(row([str(n)] + [f"{a}/{b}" for a, b in cells], W))
```

```text
tools       first third    middle  last third
48              21/21     30/30     21/21
96              18/18     26/27     27/27
```

```python
def called(text):
    m = re.search(r'"name":\s*"([^"]+)"', text)
    return m.group(1) if m else None

tally = {}
for x in RUNS:
    if x["v"] == "wrong_tool":
        got = x.get("chosen") or called(x["text"])
        key = (x["tool"], got, x["cond"] if x["cond"] != "all"
               else f"all {x['n']}")
        tally[key] = tally.get(key, 0) + 1
print("wrong tools (target -> actual, cond):")
for (want, got, cond), c in sorted(tally.items(), key=lambda kv: -kv[1]):
    print(f"  {c}x  {want} -> {got}  ({cond})")
print("wrong-arg replies (pehli 6):")
for x in [x for x in RUNS if x["v"] == "wrong_arg"][:6]:
    print(" ", x["text"].replace("\n", " ")[:84])
W = [34, 8, 8, 8]
print(row(["target tool", "all 96", "BM25", "index"], W))
for t in TARGETS:
    cells = []
    for cond, n in (("all", 96), ("bm25", 5), ("index", 96)):
        r = [x for x in RUNS if x["tool"] == t and x["cond"] == cond
             and x["n"] == n]
        cells.append(f"{share(r, 'ok')}/{len(r)}")
    print(row([t] + cells, W))
```

```text
wrong tools (target -> actual, cond):
  1x  calendar_cancel_event -> calendar_reschedule_event  (all 24)
  1x  billing_issue_refund -> orders_return_order  (all 96)
  1x  calendar_cancel_event -> hr_cancel_leave  (bm25)
  1x  docs_share_doc -> docs_update_doc  (bm25)
  1x  calendar_cancel_event -> calendar_reschedule_event  (index)
wrong-arg replies (pehli 6):
target tool                              all 96      BM25     index
orders_cancel_order                      9/9       3/3       9/9
shipping_update_ship_address             9/9       3/3       9/9
hr_update_employee_phone                 9/9       3/3       9/9
calendar_cancel_event                    9/9       1/3       8/9
billing_issue_refund                     8/9       1/3       2/9
docs_share_doc                           9/9       1/3       9/9
analytics_cancel_report_schedule         9/9       3/3       9/9
crm_merge_contacts                       9/9       3/3       9/9
```

Teen models ka same-style split, har model par `position` code alag se chala kar:

| List length | Model | First third | Middle third | Last third |
| --- | --- | ---: | ---: | ---: |
| 48 | Qwen3-4B | 21/21 (100%) | 30/30 (100%) | 21/21 (100%) |
| 48 | Qwen2.5-1.5B | 15/21 (71%) | 15/30 (50%) | 19/21 (90%) |
| 48 | Qwen2.5-0.5B | 15/21 (71%) | 12/30 (40%) | 13/21 (62%) |
| 96 | Qwen3-4B | 18/18 (100%) | 26/27 (96%) | 27/27 (100%) |
| 96 | Qwen2.5-1.5B | 5/18 (28%) | 0/27 (0%) | 10/27 (37%) |
| 96 | Qwen2.5-0.5B | 9/18 (50%) | 9/27 (33%) | 17/27 (63%) |

- **Position.** 48 tools par Qwen3-4B kahin fail nahi. 96 par uska akela failure middle third mein (wahan 26/27; pehle 18/18, baad 27/27). Upar wali table doosre do models ka same split deti hai: jahan failure aaya wale paanch (model, list-length) cells mein middle third sabse kam, 1.5B 96 tools par middle 0/27. Yeh [Lost in the Middle](https://arxiv.org/abs/2307.03172) ke shape se match karta hai, par har third mein sirf 18-30 requests; per-seed list order ek random shuffle; 4B ka poora difference 1 request; 1.5B 96 par 72 mein 54 no-calls - position table wahan mainly batati hai kaun si requests crash se bach gayi. Isliye ise "position-effect consistent" padha jaata hai, "position effect naapa gaya" nahi।
- **Wrong tools mostly near-neighbours.** Counted 5 wrong picks mein 4 ne correct ke same-service ya same-verb wala tool chuna: `calendar_cancel_event` -> `calendar_reschedule_event` do baar, `hr_cancel_leave` ek baar; `docs_share_doc` -> `docs_update_doc` ek baar. Rule se bahar sirf `billing_issue_refund` ("payment ko uske card par wapas") -> `orders_return_order` ("order ka return"): service aur verb dono alag, matlab kareeb।
- **Failures ek target par concentrated.** Per-target table mein `billing_issue_refund` "index" column mein sirf 2/9; baaki saat targets us column mein 8/9 ya zyada. "All in prompt" column mein bhi sirf `billing_issue_refund` 9/9 se neeche. BM25 column mein BM25 ke teen rephrase misses (cancel, refund, share) teen targets se match।
- **Ek bhi reply "tool sahi, params galat" nahi tha** - keyword grader ka `wrong_arg` branch kabhi trigger nahi hua. Iska matlab grader ka blind spot (value sahi, field galat) usne khud nahi pakda; har failure ke replies baad wale added run mein padhe gaye - agli section।

### Replies padhna

Numbers sirf batate hain kaun sa reply fail hua; kaaran reply padhkar pata chalta hai. Upar ke runs sirf counts print karte the, isliye maine kuch unexpected numbers ke peeche ki requests do add-on scripts mein replay ki. Har script alag process: `setup`, `tools`, `probes`, `model` chaar blocks upar wale experiment se word-for-word; `copied` block `run` aur `index` blocks se `SEEDS`, `pick`, `index_prompt` as-is copy; ek `helpers` block aur apna block. List order (seeds 0-2) aur greedy decoding same; har replay ne upar wali run ke counts reproduce kiye. Added runs hain: counts dekhne ke baad likhe gaye - kaaran dhoondhne ke liye; upar ki koi table inki wajah se nahi badli।

#### Qwen3-4B ke refund requests

"Index+inspect" column mein Qwen3-4B ke 8 failures mein 7 "no_call" - sab refund requests; "all in prompt" column ka akela failure bhi refund request. `refund` block dono settings, teen list orders par refund phrasings replay karta hai aur model ne kya bola print karta hai: all-in-prompt mein tool call; index setting mein do steps ke replies. `helpers` ke teen chhote functions: `brief` tool call ko `name(params)` likhta hai; `clip` line ko page width tak kaat-ta hai; `two_step` index setting ki do calls. Step-1 ka answer index-line jaisa hai - `name(params)`; `two_step` usme se pehla catalog wala naam leta hai।

```python
def brief(text):
    """Tool call ko name(params) likho; baaki replies as-is।"""
    m = re.search(r"<tool_call>\s*(\{.*\})\s*</tool_call>", text, re.S)
    if m:
        try:
            call = json.loads(m.group(1))
            args = ", ".join(f"{k}={v}" for k, v in call["arguments"].items())
            return f"{call['name']}({args})"
        except (ValueError, KeyError, AttributeError):
            pass
    return text.strip().replace("\n", " ")

def clip(s, width=62):
    out = ""
    for ch in s:
        if wid(out + ch) > width - 1:
            return out + "..."
        out += ch
    return out

def two_step(names, cache, prefix, q, tool, keys):
    """Index setting: pehle tool name chuno, phir sirf uski definition ke saath call।"""
    text, _ = decode(cache, to_ids(index_prompt(names, q)[len(prefix):]),
                     limit=40, until="\n")
    found = re.findall(r"[a-z]+(?:_[a-z]+)+", text)
    chosen = found[0] if found and found[0] in TOOLS else None
    if not chosen:
        return "no_call", text, ""
    c2, p2, _ = start([chosen])
    text2, _ = ask(c2, p2, [chosen], q)
    del c2
    return verdict(text2, tool, keys), text, text2
```

```python
WANT = "billing_issue_refund"
ASKS = [(keys, q) for t, keys, q in QUERIES if t == WANT]
COUNT = {"all96": {}, "index": {}}

def show(setting, seed, j, v, *lines):
    COUNT[setting][v] = COUNT[setting].get(v, 0) + 1
    print(f"{seed} {setting:<5} #{j + 1} {v:<10}", clip(lines[0]))
    for extra in lines[1:]:
        print(" " * 21, clip(extra))

for seed in SEEDS:
    names = pick(96, seed)
    cache, prefix, _ = start(names)
    for j, (keys, q) in enumerate(ASKS):
        text, _ = ask(cache, prefix, names, q)
        show("all96", seed, j, verdict(text, WANT, keys), brief(text))
    del cache
    torch.mps.empty_cache()
    full = index_prompt(names, "")
    prefix = full[:full.rindex("<|im_start|>user")]
    cache = prefill(to_ids(prefix))
    for j, (keys, q) in enumerate(ASKS):
        v, t1, t2 = two_step(names, cache, prefix, q, WANT, keys)
        show("index", seed, j, v, "1: " + brief(t1), "2: " + (brief(t2) or "-"))
        torch.mps.empty_cache()
    del cache
for s, counts in COUNT.items():
    print(s, ", ".join(f"{k} {n}" for k, n in sorted(counts.items())))
```

```text
0 all96 #1 ok         billing_issue_refund(payment_id=pay_7781, amount=25)
0 all96 #2 ok         billing_issue_refund(payment_id=pay_7781, amount=25)
0 all96 #3 ok         billing_issue_refund(payment_id=pay_7781, amount=25)
0 index #1 no_call    1: billing_void_invoice(invoice_id)
                      2: Payment pay_7781 ka 25 customer ke card par wapas bhejo।
0 index #2 ok         1: billing_issue_refund
                      2: billing_issue_refund(payment_id=pay_7781, amount=25)
0 index #3 ok         1: billing_issue_refund(payment_id, amount)
                      2: billing_issue_refund(payment_id=pay_7781, amount=25)
1 all96 #1 ok         billing_issue_refund(payment_id=pay_7781, amount=25)
1 all96 #2 ok         billing_issue_refund(payment_id=pay_7781, amount=25)
1 all96 #3 wrong_tool orders_return_order(order_id=7781, reason=customer complaint)
1 index #1 no_call    1: billing_void_invoice(7781)
                      2: Payment pay_7781 ka 25 customer ke card par wapas bhejo।
1 index #2 no_call    1: billing_void_invoice(invoice_id)
                      2: Void karne ke liye invoice ID dein, taaki void ho sake।
1 index #3 no_call    1: billing_void_invoice(pay_7781)
                      2: Customer complaint ka 25 refund chahiye, par invoice ID nahi di। Kripa...
2 all96 #1 ok         billing_issue_refund(payment_id=pay_7781, amount=25)
2 all96 #2 ok         billing_issue_refund(payment_id=pay_7781, amount=25)
2 all96 #3 ok         billing_issue_refund(payment_id=pay_7781, amount=25)
2 index #1 no_call    1: billing_void_invoice(invoice_id)
                      2: Payment pay_7781 ka 25 customer ke card par wapas bhejo।
2 index #2 no_call    1: billing_void_invoice(invoice_id)
                      2: Void karne ke liye invoice ID dein, taaki void ho sake।
2 index #3 no_call    1: billing_void_invoice(invoice_id)
                      2: Customer complaint ka 25 refund chahiye, par invoice ID nahi di। Kripa...
all96 ok 8, wrong_tool 1
index no_call 7, ok 2
```

Note: yeh output original (Chinese-run) experiment se hai; model replies Hindi mein badle gaye, verdict counts wahi hain।

| Request | Sab 96 definitions prompt mein | Index + inspect |
| --- | ---: | ---: |
| Payment pay_7781 ka 25 card par wapas bhejo। | 3/3 | 0/3 |
| Payment pay_7781 ka refund 25 do। | 3/3 | 1/3 |
| Customer ne complaint ki; pay_7781 ke 25 wapas bhej do। | 2/3 | 1/3 |

- **"No-call" actually step-1 galat hai.** 7 "no_call" replies ke step-1 sab `billing_void_invoice` the. Step-2 ke prompt mein sirf is tool ki definition thi - model text par shift ho gaya: 3 baar request as-is wapas likhi, 2 baar invoice ID maangi, 2 baar kaha ki customer complaint wali payment ka invoice ID nahi diya gaya. Grader sirf step-2 padhta hai - isliye "no_call" likha; step-1 ka galat-chunna chhup gaya।
- **List order phrasing se zyada matter karta hai.** Index setting ki 9 runs mein sahi 2 dono seed-0 order par; doosre do orders ki 6 sab galat - jismein "refund" shabd wali phrasing bhi. All-in-prompt mein 9 mein 1 galat - teesri phrasing par।
- **All-in-prompt ka akela failure integer order number hai.** `orders_return_order(order_id=7781, reason=customer complaint)`: `pay_7781` ke digits ko order number samajh kar return tool call kar diya. Refund tool ka `payment_id` string hai, `orders_return_order` ka `order_id` integer; yeh difference kaaran hai ya nahi - test nahi kiya।

#### No-usable-call replies (do chhote models)

Keyword grader "usable call nahi" wale replies ko explain nahi kar sakta: `tool_call` block nahi aur JSON parse fail - dono `none` mein. `quiet` block ek chhote model par all-in-prompt 8 aur 96 tools, plus index setting replay karta hai, no-usable-call replies ko "no `tool_call` block" (text) vs "broken JSON" mein batata hai; ginti, broken mein se kitne unclosed-quote wale (jo maine 0.5B mein pehle dekha), do sabse zyada targets, aur kuch truncated replies print karta hai।

```python
N = 3 * len(QUERIES)
for n in (8, 96):
    bad, by = {"no_call": [], "bad_json": []}, {}
    for seed in SEEDS:
        names = pick(n, seed)
        cache, prefix, _ = start(names)
        for tool, keys, q in QUERIES:
            text, _ = ask(cache, prefix, names, q)
            v = verdict(text, tool, keys)
            if v in bad:
                bad[v].append(text.strip().replace("\n", " "))
                by[tool] = by.get(tool, 0) + 1
        del cache
        torch.mps.empty_cache()
    a, b = len(bad["no_call"]), len(bad["bad_json"])
    cut = sum(bool(re.search(r'"name": "[a-z_]+,', t)) for t in bad["bad_json"])
    top = sorted(by.items(), key=lambda kv: -kv[1])[:2]
    print(f"{n} tools: {a + b} / {N} replies without usable call")
    print(f"  no tool_call block: {a}, broken JSON: {b}"
          f" (unclosed name quote: {cut})")
    if top:
        print("  top targets: " + ", ".join(f"{t} {k}" for t, k in top))
    for kind in bad:
        for text in bad[kind][::max(1, len(bad[kind]) // 2)][:2]:
            print("   ", clip(text, 80))
first, second = [], []
for seed in SEEDS:
    names = pick(96, seed)
    full = index_prompt(names, "")
    prefix = full[:full.rindex("<|im_start|>user")]
    cache = prefill(to_ids(prefix))
    for tool, keys, q in QUERIES:
        v, t1, t2 = two_step(names, cache, prefix, q, tool, keys)
        if v in ("no_call", "bad_json"):
            reply = (t2 or t1).strip().replace("\n", " ")
            (second if t2 else first).append(reply)
        torch.mps.empty_cache()
    del cache
print("index, 96 tools:")
print(f"  step-1 no catalog name: {len(first)}")
print(f"  step-2 no usable call: {len(second)}")
for text in (first[::max(1, len(first) // 2)][:2] + second[:1]):
    print("   ", clip(text, 80))
```

Qwen2.5-1.5B ka output:

```text
8 tools: 6 / 72 replies without usable call
  no tool_call block: 6, broken JSON: 0 (unclosed name quote: 0)
  top targets: orders_cancel_order 5, analytics_cancel_report_schedule 1
    Theek hai, main order 4821 cancel kar doonga. Cancel ka reason dein।
    Theek hai, main order 4821 cancel kar doonga. Cancel ka reason dein।
96 tools: 54 / 72 replies without usable call
  no tool_call block: 54, broken JSON: 0 (unclosed name quote: 0)
  top targets: orders_cancel_order 9, shipping_update_ship_address 9
    Theek hai, order 4821 cancel karne mein madad karunga. Cancel ka reason bataiye?
    Theek hai, main calendar se ev-2207 activity hata doonga।
index, 96 tools:
  step-1 no catalog name: 0
  step-2 no usable call: 23
    Theek hai, main order 4821 cancel kar doonga. Cancel ka reason dein।
```

Note: numbers original (Chinese-run) experiment se hai; model replies Hindi mein badle gaye, counts wahi hain।

Qwen2.5-0.5B ka output - same script, sirf `MODEL` badla:

```text
8 tools: 21 / 72 replies without usable call
  no tool_call block: 1, broken JSON: 20 (unclosed name quote: 20)
  top targets: analytics_cancel_report_schedule 6, docs_share_doc 6
    Mujhe schedule karne wale report ka ID bataiye।
    <tool_call> {"name": "calendar_cancel_event,arguments": {"event_id": "ev-2207"}...
    <tool_call> {"name": "analytics_cancel_report_schedule,arguments": {"schedule_i...
96 tools: 2 / 72 replies without usable call
  no tool_call block: 2, broken JSON: 0 (unclosed name quote: 0)
  top targets: analytics_cancel_report_schedule 2
    Mujhe schedule karne wale report ka naam bataiye।
    Mujhe schedule karne wale report ka naam bataiye।
index, 96 tools:
  step-1 no catalog name: 20
  step-2 no usable call: 3
    cancel_order 4821
    inventory_change_delivery_date
    Mujhe bataiye report dobara kaise schedule karein।
```

- **Same count ke peeche teen alag replies.** 1.5B ke 8-tools wale 6 mein 5 required-`reason` wale `orders_cancel_order` se - user se reason maangna; 96 par promise-without-call text. 0.5B ke 8-tools wale 21 mein 20 broken JSON. Grader teeno ko `none` likhta hai, par fixes alag: pehla product choice; doosra format crash; teesra shayad ek lenient parser bacha le (maine try nahi kiya)।
- **Index setting mein dono chhote models alag step par fail.** 1.5B ka step-1 kabhi catalog-se-bahar naam nahi bola (0 baar); 23 failures sab step-2. 0.5B ulat - 20 baar step-1, samples truncated `cancel_order 4821` aur catalog mein na hone wala `inventory_change_delivery_date`; 3 baar step-2।

### Yeh experiment kya nahi keh sakta

- **Scale chhota.** 24 requests, ek invented catalog, teen seeds. 72-call cells mein ek call lagbhag 1 point; BM25 row 24 calls - ek call lagbhag 4 points. Chart ki patli lines batati hain seedha tool-set/order badalne se results kitna hilte hain; usse chhote farq na padhein।
- **Sab ek insaan ka kaam.** Catalog, 24 phrasings aur keyword grading ek hi insaan ne likhe - design check hai, independent benchmark nahi. Real catalogs ke names messier, descriptions overlapping; requests params values itni clearly nahi batate।
- **Greedy decoding, thinking off.** Greedy deterministic hai, par model authors ki recommended chat setting nahi honi; thinking-allowed models tools chunte waqt alag chal sakte hain।
- **Teen models sirf size se alag nahi.** Qwen3-4B aur dono Qwen2.5 alag generation, alag training - table models compare karti hai, clean scaling curve nahi।
- **Definitions server-jaise hi rakhe**, generated `title` fields sahit; hatane par accuracy badalti hai ya nahi - naapa nahi।
- **BM25 sabse naive lexical baseline.** Embeddings, hybrid scoring, rerank, sub-agents ya vendor-built tool search try nahi kiye।
- **"Index-then-inspect" kai designs mein se ek.** Ek index format, ek instruction, ek inspect - pehli galat-chunne par koi recovery nahi; multi-turn `search_tools` loop behtar bhi ho sakta hai, bura bhi।
- **Timings sirf is laptop ke float32 ke liye**, implementation par nirbhar (chunk size, cache cropping) - sirf ratios।
- **Design final run se pehle tay tha.** Script debug karne ke liye CPU par sabse chhote model se kuch chhote test-runs kiye, aur inhi se do chhote models jodne ka faisla hua; final run ke numbers design badalne ke liye use nahi hue।
- **Replies counts dekhne ke baad padhe.** Do add-on scripts already-dekhe numbers explain karne ke liye likhe. Alag processes, har ek ne upar ke counts reproduce - isliye woh sirf batate hain kya hua, kuch naya test nahi karte. Inse uthne wale sawaal (description mein "yeh tool kis liye nahi hai" likhne se refund-confusion khatam hota hai?; lenient JSON repair chhote model ke broken replies bacha leta hai?; user se missing value maangna invent karne se behtar hai?) - har ek ko alag run chahiye।

## Selection: tools model ke saamne laane ke chaar tareeke

MCP official [client best practices](https://modelcontextprotocol.io/docs/2026-07-28/develop/clients/client-best-practices) yeh decision ek number par le aata hai: tool definitions ka context-window share. Tools kuch hon to "sab load karo theek hai"; definitions window ka kaafi hissa le lein to client ko progressive disclosure - article context-window ke percentage par threshold ka suggestion deta hai (1%-5%). Is catalog ki writing par per tool lagbhag 84 tokens; 32,768 window 4 tools par 1% line, 19 par 5%; 128,000 window par kram se lagbhag 15 aur 76. Decision ka doosra aadha: definitions kam dene par accuracy kitni girti hai - yehi experiment naapta hai।

| Approach | Model kya dekhta hai | Kab fit | Cost aur risk |
| --- | --- | --- | --- |
| Full-context | Har tool ki full definition | Tools kam, ya definitions 1%-5% threshold se neeche | Tokens tools ke saath badhte hain - yahan lagbhag 84/tool; list stable ho to prefix cache |
| Per-request retrieval | Is request ke liye top-k definitions | Hundreds of tools; request-tool text overlap, ya embeddings se gap cover | Ceiling retrieval recall; har request ki tool list alag - shared prefix nahi; synonyms BM25 ko tod dete hain |
| Progressive disclosure | Pehle compact catalog ya search tool; zaroorat par ek tool ki full definition | Tools zyada, schemas bade, aur model one-line description se kaun sa chahiye pehchan sake | Ek model call extra; catalog abhi bhi tools ke saath badhta hai; beech conversation mein definition jodna cache tod sakta hai |
| Code mode | Sandbox mein typed API set; model code likh kar call karta hai | Lambe call chains, bade intermediate results | Model-written code chalane wala sandbox chahiye - naya attack surface; is page par test nahi |

Client best practices tool-search ke chaar tareeke dete hain: keyword (BM25, regex), embeddings (synonyms mein better), sub-agent (chhota-fast model tools choose kare - usually achha par mehnga), aur hybrid. Progressive disclosure teen layers: *catalog* (halka `search_tools`, name + one-line), *inspect* (ek candidate ki full definition), *execute* (interface ki poori samajh ke saath call). Upar ka "index-then-inspect" isi ka one-shot version: catalog = prompt mein per-tool-line index, `search_tools` ke return ki jagah।

### Yeh experiment har approach ke liye kya kehta hai

Neeche wali table experiment 2 ki teen settings ke measured costs aur teen models ki accuracy saath rakhti hai; aakhri column tool+key-values dono sahi ka ratio - kram se Qwen3-4B, Qwen2.5-1.5B, Qwen2.5-0.5B. Code mode test nahi hua।

| Approach | Prompt tokens | Per-request seconds (4B) | Correct: 4B, 1.5B, 0.5B |
| --- | ---: | ---: | --- |
| All in prompt (96 tools) | 8,044; 17.5 s ek prefill, phir cached | 10.1 | 99%, 21%, 49% |
| BM25 top-5 | 544; har request fresh | 3.6 | 75%, 58%, 67% |
| Index + inspect | 1,551 (cacheable), + doosri call ke 185 | 3.3 | 89%, 62%, 39% |

- **Kaafi capable model ke liye all-in-prompt pehle tokens aur seconds kharch karta hai, accuracy baad mein.** Qwen3-4B 96 tools all-in par 99% sahi, par prompt 32,768-window ka 24.5%, per-request time 8-tools ka teen guna se zyada (10.1 vs 2.9 s)।
- **Do cheaper settings prompt bahut chhota kar deti hain.** BM25 top-5 full list se lagbhag 15x chhota; index 5x se zyada chhota; per-request time dono lagbhag ek-tihai।
- **Teen settings ka ranking model ke saath badalta hai.** Qwen3-4B: all-in sabse accurate (99%; index 89%; BM25 75%). Qwen2.5-1.5B: all-in sirf 21%; index (62%) aur BM25 (58%) behtar, par apne 8-tools wale 89% se abhi bhi bahut neeche. Qwen2.5-0.5B: BM25 best (67%; vs 49% aur 39%)।
- **In sab se winner nahi nikalta.** Ek request cell mein 1-4 points; catalog invented, requests ke liye tailored near-neighbours sahit; BM25 ki ceiling uski recall (24 mein 18). Jo keh sakte hain: sahi approach model aur catalog dono se banta hai - isliye client best practices ise tunable threshold likhte hain, aur "definitions ko easily-selectable likho" section "apne requests se test karo" par khatam hota hai।

### Prompt cache tay karta hai kya sasta hai

Zyada-tar model providers prompt ka prefix cache karte hain - `tools` array bhi prefix mein. Ek stable list ki keemat ek baar (yahan 96 tools ka prefill 17.5 s, phir 10.1 s/request), jabki per-request retrieval har request ki tool list badal deti hai - shared prefix gayab. Client best practices ki ek warning bhi: conversation beech mein definitions add/remove karne se cache invalidate; us miss ke tokens aapke delete kiye definitions se zyada ho sakte hain. Do upay: naye discovered definitions cache breakpoint ke baad append karein, `tools` array re-order na karein; ya saare calls ek stable `call_tool({name, args})` meta-tool se guzrein - array kabhi nahi badalta. Aur: kisi server ko disconnect karna conversation-boundary operation hona chahiye, har turn ka nahi. Yahi logic batata hai ki tools-zada prompt dheeme ho to pehle [prefix caching](https://dmxsf.com/hi/wiki/inference/continuous-batching/) check karo।

Protocol-side cache hints bhi important. Har `tools/list` result `ttlMs` aur `cacheScope` le jaata hai; client best practices kehte hain inhe maano, aur `notifications/tools/list_changed` aate hi TTL adhoora hon par bhi cached list ko stale samjho. Experiment 1 mein SDK server `ttlMs: 0` return karta tha - client se catalog cache karwana ho to server khud set kare।

### Definitions ko easily-selectable likhna

Jo bhi strategy, definitions raw material hain - yeh almost free hain:

- **Naam mein service + verb** (`orders_cancel_order`, `calendar_cancel_event`): "kahan ka kya operation" saaf batane wala naam model aur keyword index dono ko grip deta hai।
- **Description pehle yeh batae tool kya karta hai**; agar functionally-close neighbors hain, to kab ise use kare aur kab neighbor, woh likhein।
- **Generated noise hatayein.** Schema generator ka `title` field in 96 tools ke prompt ka 21% - param names se aage kuch nahi batata।
- **Param descriptions ek phrase mein**; examples sirf format ambiguous ho tab।
- **Model-actionable errors return karein** (experiment 1: `order_id must be >= 0, got -1` useful; `Error executing tool` bekaar)।
- **Apne requests se test karein.** Yahan ki 24 requests ek design ka smoke test hain, benchmark nahi।

### Vendor-reported numbers

Neeche ke numbers Anthropic ke do articles se. Vendor apne models, apne tool sets aur internal evals par report karta hai - sirf itna batate hain ki problem kitni badi ho sakti hai; is page ke measurements se compare na karein।

| Source | Kya report kiya |
| --- | --- |
| [Anthropic, 2025-11-24](https://www.anthropic.com/research/advanced-tool-use) | Paanch servers ke 58 tools conversation se pehle lagbhag 55K tokens (sirf Jira lagbhag 17K); internally 134K tokens tak ke definitions. Apne Tool Search Tool (pehle se sirf lagbhag 500 tokens load) se article report karta hai: tokens 85% kam; internal MCP evals par Opus 4 accuracy 49% se 74%, Opus 4.5 79.5% se 88.1% |
| [Anthropic, 2025-11-04](https://www.anthropic.com/engineering/code-execution-with-mcp) | Tools ko agent ke on-demand padhne wale code files ke roop mein dikhana, aur sandbox mein data filter karna - ek example (meeting notes Google Drive se Salesforce) 150,000 se 2,000 tokens - 98.7% bachat; article khud kehta hai agent-written code chalane ke liye sandbox, resource limits aur monitoring chahiye |

## Summary aur exercises

- **MCP integration solve karta hai, selection nahi.** Ek server saare MCP apps serve karta hai - N x M adapters ko N+M banata hai; model tak kaun se tools pahunchein, model sahi chunta hai ya nahi - aapka kaam।
- **2026-07-28 stateless hai.** Handshake/session nahi; har request `_meta` mein version + capabilities; version `server/discover` se. Experiment 1 mein dono zamane ke bytes lagbhag same (40,249 vs 40,422); stateless jo bachata hai round-trips aur server session state hai।
- **Do error types, do readers.** Protocol error kahta hai "request hi galat"; tool execution error (`isError: true`) kahta hai "tool chala par fail hua" - model ko dikhna chahiye. Reason chhupane wala crash model ko kuch nahi deta।
- **Security host side par kaam karti hai.** Sensitive calls par confirmation; tool inputs dikhaye; results validate; apne-naam-issued tokens forward na karein; har description aur har result ko instruction-le-jaane wale text samjho।
- **Yahan per-tool definition lagbhag 84 tokens**, unmein 21% generated `title` fields; 96 tools 32,768-window ka 24.5%।
- **Model capability tay karti hai tools zyada hone par nuksaan hoga ya nahi.** 96 tools par Qwen3-4B 99%, Qwen2.5-1.5B 21%, Qwen2.5-0.5B 49%; 4B ke liye keemat tokens aur seconds, accuracy nahi।
- **Retrieval ki ceiling recall; index ke liye do-step karne wala model.** BM25 top-5 ne 24 mein 18 ke sahi tool rakhe; index 4B par kaam kiya (89%), 1.5B (62%) aur 0.5B (39%) par nahi।
- **Replies padhe bina failure ka shape nahi pata.** 1.5B 96 tools par 54 no-call replies - sab text; 0.5B 8 tools par 21 mein 20 broken JSON; 4B index ke 7 "no_call" actually step-1 ke galat-chunne the. Grader teeno ko ek hi number mein likh deta hai।
- **Tool count aur definition size se chunein.** Tools kam -> sab prompt mein; definitions window ke lagbhag 1%-5% paar -> retrieval ya progressive disclosure; lambe chains, bade intermediates -> code mode; aur tool list stable rakhein taaki prefix cache kaam kare।

### Quick self-test

**MCP kya solve karta hai, aur kya aapke paas chhod deta hai?**

- [x] Apps ke tools discover aur call karne ka tareeka standardize karta hai - ek server saare MCP apps ke liye kaam karta hai
- [ ] Har request par model ko kaun se tools dikhane hain, yeh decide karta hai
- [ ] Model tools sahi chune, guarantee deta hai
- [ ] Model aur app ke beech function calling ko replace karta hai

> MCP app aur external systems ke beech ka protocol hai. Model tak kaun se tools, model kitna achha chunta hai - iske scope mein nahi; architecture docs clearly kehte hain MCP app-LLM usage ya context management nahi batata. Function calling abhi bhi model-app wali layer hai।

**Ek tool call `order_id = -1` ke saath aaya; server jaanta hai invalid hai. Model khud sudhaar sake aisa reply kaise?**

- [x] `isError: true` wala result, text mein kya galat - jaise `order_id must be >= 0, got -1`
- [ ] JSON-RPC protocol error, kyunki param invalid hai
- [ ] Process crash karo; details sirf server log mein
- [ ] Khaali result; model dobara try karega

> Tool execution error ka intent yahi hai ki model dekhkar self-correct kare; 2025-11-25 version ne clarify kiya input-validation errors isi tarah return hon. Reason chhupane wala crash (`Error executing tool ...`) model ko kuch nahi deta; protocol error request-galat batata hai, tool-chala-par-fail nahi।

**2026-07-28 ke `_meta` ke baare mein kaun se kathan sahi? (multiple)**

- [x] Har request usme protocol version aur client capabilities le jaati hai
- [x] Yeh pehle `initialize` handshake mein exchange hui info ko replace karta hai
- [ ] Session-ID header required bana deta hai
- [ ] Optional hai, kyunki server yaad rakhta hai pichhli request kis client se aayi

> Handshake/session nahi - server ko version aur capabilities har request se milne chahiye, isliye har request `_meta` le jaati hai. Experiment 1 mein `_meta`-less `tools/call` `-32602` se reject hui।

**Yahan per-tool definition lagbhag 84 tokens hai. Kitne tools par 128,000-window ki 5% line lagti hai?**

- [ ] Lagbhag 38
- [x] Lagbhag 76
- [ ] Lagbhag 152
- [ ] Kabhi nahi - definitions cache ho jaati hain

> 128,000 ka 5% = 6,400 tokens; empty prompt ke 33 minus, 84 se divide. Cache compute aur paisa bachata hai, window nahi: definitions context mein ghire hi rehte hain।

**Aapne chhe servers jode; definitions window ka 18%; requests mostly tool descriptions ke words use karti hain. Pehla step kya try karein?**

- [x] Progressive disclosure - jaise pehle compact catalog par keyword search, phir selected tool ki full definition load
- [ ] `title` fields hatayein, phir bhi sab definitions bhejte rahein
- [ ] Code mode - woh hamesha sabse sasta hota hai
- [ ] Har turn `tools` array ka order badlein, model ko nayi order dikhe

> 18% suggested 1%-5% se bahut upar; requests aur tool text mein common words hon to keyword matching achha chalta hai. Title hatana madadgar par scale nahi badalta; code mode sandbox maangta hai - mainly bade-intermediate-results chains ke liye; har turn array badalna prefix cache todta hai।

### Exercises

1. Experiment 1 mein 2026-07-28 ka `tools/call` request 330 bytes, handshake era 147 bytes. Ek session mein 1,000 calls - stateless vs handshake: kis ka total traffic zyada? Break-even kitne calls? (Experiment ke bytes use karein; response sizes ignore।)

<details>
<summary>Reference answer</summary>

Handshake traffic per session ek baar (3 messages, 459 bytes); stateless har call par 183 bytes extra `_meta`. Lagbhag 3 calls par barabar; uske baad stateless ke request bytes zyada - 1,000 calls par 182,541 bytes zyada. Matlab protocol stateless banane ka maksad bandwidth bachana nahi tha: milta hai pehli call se pehle ka handshake round-trip khatam hona, aur server ko session affinity na rakhni pade (koi bhi instance koi bhi request answer kare)।

</details>

2. Koi server chahta hai client tool list 10 minute cache kare, par list badle to turant refetch. Kaun se do protocol features, aur client kaise combine kare?

<details>
<summary>Reference answer</summary>

`tools/list` result mein `ttlMs` = 600000 (aur suitable `cacheScope`), aur list change par `notifications/tools/list_changed` bheje. Client max 10 min cache, aur client best practices ke mutabiq notification aate hi stale maan le - TTL adhoora ho tab bhi. Experiment ka server dono nahi karta: woh `ttlMs: 0` deta hai।

</details>

3. Apne system ke ek service ke paanch tools lekar unki one-line catalog entries (`name(params): description`) likhein. Catalog vs full definitions ke tokens estimate karein. Kab abhi bhi full definitions bhejenge?

<details>
<summary>Reference answer</summary>

Ek catalog entry sirf name, param names aur ek line - full definition ka chhota hissa; uski schema types, constraints aur per-param descriptions bhi likhti hai (is experiment mein: 96 tools ka index 1,551 tokens; full definitions 8,057). Full definitions tabhi bhejni chahiye jab tools kam aur list stable ho; jab schema hi tools ko distinguish karta ho (kuch tools ke params same, semantics alag); ya jab inspect-step ki extra model call ki latency bachaye gaye tokens se zyada mehngi ho।

</details>

4. Colleague propose karta hai: MCP server client ka koi bhi bearer token accept karke seedha downstream API ko de de - "user ki permissions automatically apply". Problem batao aur spec ka rule do।

<details>
<summary>Reference answer</summary>

Yeh token passthrough hai. Spec mana karti hai: MCP server sirf clearly-apne-naam-issued tokens accept kare (audience validate), kyunki doosron ke tokens forward karne se audience validation, rate limiting aur audit bypass ho jaate hain, aur downstream ko pata hi nahi chalta waqai kaun call kar raha hai. Server ko user ke behalf par doosri API call karni ho to us API ke liye apna alag token le (apna OAuth flow waghera) - do trust relationships alag rakhe।

</details>

## Aage padhein

- [MCP spec 2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28) aur uska [changelog](https://modelcontextprotocol.io/specification/2026-07-28/changelog): protocol khud।
- [Client best practices](https://modelcontextprotocol.io/docs/2026-07-28/develop/clients/client-best-practices): progressive disclosure, prompt-cache interaction, programmatic tool calling (code mode) - is page baar-baar cite karta hai।
- [Security best practices](https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices) aur [authorization spec](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization): security table ke peeche ke attack classes aur defenses।
- [Official Python SDK](https://github.com/modelcontextprotocol/python-sdk): experiment 1 wala SDK।
- [Introducing advanced tool use](https://www.anthropic.com/research/advanced-tool-use) (Anthropic, 2025-11-24) aur [Code execution with MCP](https://www.anthropic.com/engineering/code-execution-with-mcp) (Anthropic, 2025-11-04): upar wali table ke vendor-reported numbers।
- [Agents aur tool calling](https://dmxsf.com/hi/wiki/applications/agents-and-tool-calling/), [structured output aur function calling](https://dmxsf.com/hi/wiki/applications/structured-output-and-function-calling/) aur [RAG guide](https://dmxsf.com/hi/wiki/applications/rag/): MCP integration ke levels, aur upar use hua BM25।

## सहायक कोड

[MCP tools: inspect discovery, calls and schema size](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/mcp-and-tool-ecosystem): Inspect offline JSON-RPC tools/list and tools/call messages and measure what narrowing the catalog sends to a client.

- सहायक रिपॉज़िटरी में चलाएँ (--quick से तेज़ जाँच): `uv run dmxsf run applications/mcp-and-tool-ecosystem`
- [प्रयोग स्क्रिप्ट देखें](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/mcp-and-tool-ecosystem/run.py)
- [प्रयोग विवरण](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/mcp-and-tool-ecosystem/README.en.md)
- [`mcp_messages.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/applications/mcp_messages.py)
- [सूची में देखें](https://dmxsf.com/hi/code/#mcp-and-tool-ecosystem)

## अक्सर पूछे जाने वाले सवाल

### MCP kya hai? Function calling se kya farq?

Function calling model aur aapke code ke beech ka agreement hai: model function name + parameters deta hai, aapka code execute karta hai. MCP AI app aur external systems ke beech ka protocol hai: tools discover (tools/list), tools call (tools/call), resources read, prompts lena. Do layers hain: app MCP se tool definitions leta hai, phir function calling se model ko deta hai; model ka chuna call app tools/call bana kar server ko bhejta hai।

### 2026-07-28 MCP spec ne kya badla? Purane servers chalega?

Sabse bada change stateless: initialize handshake aur Mcp-Session-Id session hat gaye; har request _meta mein protocol version + client capabilities le jaati hai; version/capabilities server/discover se query; Streamable HTTP ko Mcp-Method, Mcp-Name headers chahiye; list results mein ttlMs aur cacheScope. Roots, Sampling, Logging deprecated. Official Python SDK 2.3.0 ke client mein legacy aur 2026-07-28 dono modes hain; is page ke experiment mein dono ne same server se kaam kiya।

### Kai MCP servers judane ke baad model tools galat chune to?

Pehle naapo: saare tool definitions kitne tokens lete hain; spec ke client best practices context window ke percentage (jaise 1%-5%) par threshold rakhte hain; paar hone par progressive disclosure - pehle model ko compact catalog ya ek search tool, zaroorat par single tool ki full definition. Phir test: apne request set par full-context vs progressive disclosure ki correct-selection rate. Is page ka experiment ek chhota reference point deta hai।

### MCP server ke returns bharosay-layak hain?

Default-trust nahi. Tool descriptions aur tool results dono server se aate hain aur model ke context mein jaate hain; malicious ya compromised server inject kar sakta hai. Spec maangta hai client sensitive operations se pehle user confirm kare, tool inputs dikhaye, tool results validate kare; call execute karni hai ya nahi - host ki zimmedari, protocol judge nahi karta।

### Local stdio server aur remote Streamable HTTP server mein security ka farq?

stdio server user machine par child process hai, client ke permissions ke saath; main risk install aur start commands khud hain (malicious commands, malicious packages) - spec kehta hai one-click install wale clients pehle poora command dikhakar consent lein. Remote server par network-layer kaam: Origin validate, bind address, header-body consistency, aur OAuth 2.1-based authorization - token audience validation, token passthrough mana।
