VKP1     b{"name":"ai_mcp","version":"1.0.0","tier":3,"tier_label":"Tier 3: AI, Vector RAG & DataFrames","category":"Model Context Protocol","description":"JSON-RPC 2.0 MCP (2025-03-26) server & client with homoiconic tool schemas, resources, prompts, stdio transport, and web/App mounting.","modules":["ai_mcp"],"homepage":"https://veko-lang.org/packages/ai_mcp"}    	README.md  :# ai_mcp

Model Context Protocol (`2025-03-26`) JSON-RPC 2.0 server and client for Veko, featuring homoiconic tool schema generation, NDJSON stdio framing, and mountable Streamable HTTP routes over `lib/web`.

## Installation

```powershell
veko pkg add ai_mcp@1.0.0
```

Import in any Veko module:

```rebol
use [mcp = ai_mcp]
```

## Architecture Notes

- **Protocol Version `2025-03-26`:** Implements `initialize`, `notifications/initialized`, `ping`, `tools/list`, `tools/call`, `resources/list`, `resources/read`, `prompts/list`, and `prompts/get`, including JSON-RPC 2.0 batch payloads.
- **Structured JSON-RPC Error Semantics:** Protocol violations return standard JSON-RPC error envelopes (`-32700` parse error, `-32600` invalid request, `-32601` method not found, `-32602` invalid params, `-32603` internal error), whereas recoverable tool runtime `err` values set `isError = true` inside the tool result content array per MCP specification.
- **Homoiconic Schema Builder:** `mcp/tool-schema` transforms quoted Veko parameter declarations (`quote [ query str 'Search query', limit i64 .optional 'Max rows' ]`) directly into JSON Schema `{ type = 'object', properties = ..., required = ... }` maps without stringly-typed boilerplate.
- **Dual Transport Support:** Run over line-delimited stdio via `mcp/handle-jsonrpc-line` or mount directly onto any `web/App` route via `mcp/mount-http` (`POST` JSON-RPC + `202 Accepted` notifications + `GET` SSE endpoint discovery).

## API Reference

### Constants

- `mcp/MCP-PROTOCOL-VERSION` -> `'2025-03-26'`
- `mcp/ERR-PARSE-ERROR` (`-32700`), `mcp/ERR-INVALID-REQUEST` (`-32600`), `mcp/ERR-METHOD-NOT-FOUND` (`-32601`), `mcp/ERR-INVALID-PARAMS` (`-32602`), `mcp/ERR-INTERNAL` (`-32603`)

### Types

- `McpServer` â€” Stateful MCP server registry (`name`, `version`, `instructions`, `tools`, `resources`, `prompts`).
- `McpTool` â€” Tool metadata and handler (`fn [args map] any`).
- `McpResource` â€” Resource URI metadata and reader (`fn [uri str] any`).
- `McpPrompt` / `McpPromptArg` â€” Prompt template definition and builder (`fn [args map] any`).
- `McpClient` â€” Multi-transport MCP client handle.

### Server Functions

- `mcp/new-server name version [/instructions instr]` -> `McpServer`
- `mcp/tool-schema spec_blk` -> `map` (JSON Schema `object` descriptor)
- `mcp/add-tool mut srv name description input_schema handler`
- `mcp/add-resource mut srv uri name description mime_type reader`
- `mcp/prompt-arg name description required` -> `McpPromptArg`
- `mcp/add-prompt mut srv name description arguments builder`
- `mcp/text-content text` -> `map`
- `mcp/prompt-message role text` -> `map`
- `mcp/handle-message mut srv msg` -> `any` (response `map`, batch `block`, or `.none`)
- `mcp/handle-jsonrpc-line mut srv line` -> `str`
- `mcp/mount-http mut app route_path srv`

### Client Functions

- `mcp/new-http-client endpoint_url [/headers extra_headers]` -> `McpClient`
- `mcp/new-app-client app route_path` -> `McpClient`
- `mcp/new-custom-client endpoint transport_fn` -> `McpClient`
- `mcp/client-initialize mut client` -> `any`
- `mcp/client-ping mut client` -> `any`
- `mcp/client-list-tools mut client` -> `any`
- `mcp/client-call-tool mut client name arguments` -> `any`
- `mcp/client-list-resources mut client` -> `any`
- `mcp/client-read-resource mut client uri` -> `any`
- `mcp/client-list-prompts mut client` -> `any`
- `mcp/client-get-prompt mut client name arguments` -> `any`

## Idiomatic Veko Example

```rebol
use [mcp = ai_mcp, web]

mut srv = mcp/new-server 'repo-assistant' '1.0.0'

schema = mcp/tool-schema (quote [
    query str 'Search query',
    limit i64 .optional 'Max rows'
])

mcp/add-tool mut srv 'search_docs' 'Search repository documentation' schema fn [args map] any [
    q = str/append '' (map/get args 'query')
    lim = as-i64 (map/get/or args 'limit' [ 5 ])
    `Matched {mold lim} docs for {q}`
]

mut app = web/new-app
mcp/mount-http mut app '/mcp' srv

mut client = mcp/new-app-client app '/mcp'
_ = mcp/client-initialize mut client
res = mcp/client-call-tool mut client 'search_docs' { query = 'concurrency', limit = 3 }
print (json/encode res)
```
²Ñ‘“ì‘·™Ú´Æ¯ŽáÀAŸ�÷k“�lÇ„ examples/demo.vk  ~// packages/ai_mcp/examples/demo.vk
// End-to-end verification suite for `ai_mcp` (MCP 2025-03-26 Server & Client).

use [mcp = ai_mcp, web]

assert-eq = fn [label str, got any, want any] [
	if got != want [
		println `[FAIL] {label}: got {mold got}, expected {mold want}`
		return (err `assertion failed: {label}`)
	]
	println `[PASS] {label}`
	.ok
]

assert-true = fn [label str, cond bool] [
	if not cond [
		println `[FAIL] {label}`
		return (err `assertion failed: {label}`)
	]
	println `[PASS] {label}`
	.ok
]

build-demo-server = fn [] mcp/McpServer [
	mut srv = mcp/new-server/instructions 'veko-knowledge-mcp' '1.0.0' 'Search docs, read specs, and draft code reviews.'

	search_schema = mcp/tool-schema (quote [
		query str 'Search query',
		limit i64 .optional 'Max rows'
	])

	mcp/add-tool mut srv 'search_docs' 'Search Veko documentation sections' search_schema fn [args map] any [
		q = str/lower (str/append '' (map/get args 'query'))
		lim = as-i64 (map/get/or args 'limit' [ 5 ])
		if q == 'fail' [
			return (err 'simulated backend timeout')
		]
		`Found {mold lim} matches for "{q}"`
	]

	calc_schema = mcp/tool-schema (quote [
		a i64 'Left operand',
		b i64 'Right operand'
	])

	mcp/add-tool mut srv 'sum_ints' 'Sum two 64-bit integers' calc_schema fn [args map] any [
		a = as-i64 (map/get args 'a')
		b = as-i64 (map/get args 'b')
		mold (a + b)
	]

	mcp/add-resource mut srv 'veko://specs/mcp' 'MCP Spec Summary' 'Protocol notes' 'text/markdown' fn [uri str] any [
		`# Resource {uri}\nTransport: JSON-RPC 2.0 (2025-03-26)`
	]

	mcp/add-prompt mut srv 'code_review' 'Structured Veko code review prompt' [
		(mcp/prompt-arg 'module' 'Target module name' true)
		(mcp/prompt-arg 'focus' 'Optional focus area' false)
	] fn [args map] any [
		mname = str/append '' (map/get args 'module')
		focus = str/append '' (map/get/or args 'focus' [ 'safety and clarity' ])
		[
			(mcp/prompt-message 'user' `Review module {mname} focusing on {focus}.`)
		]
	]

	srv
]

main = fn [] any [
	// 1. Verify homoiconic `tool-schema` generation
	schema = mcp/tool-schema (quote [ query str 'Search query', limit i64 .optional 'Max rows' ])
	_ = assert-eq/or 'tool-schema root type' (map/get schema 'type') 'object' [e -> return e]
	props = map/get schema 'properties'
	qprop = map/get props 'query'
	lprop = map/get props 'limit'
	reqs = map/get schema 'required'
	_ = assert-eq/or 'tool-schema query type' (map/get qprop 'type') 'string' [e -> return e]
	_ = assert-eq/or 'tool-schema limit type' (map/get lprop 'type') 'integer' [e -> return e]
	_ = assert-eq/or 'tool-schema required list' (len reqs) 1 [e -> return e]
	_ = assert-eq/or 'tool-schema required[0]' reqs[0] 'query' [e -> return e]

	// 2. Verify NDJSON stdio line dispatcher (`handle-jsonrpc-line`) & JSON-RPC error codes
	mut srv = build-demo-server

	init_line = mcp/handle-jsonrpc-line mut srv (json/encode {
		jsonrpc = '2.0'
		id      = 1
		method  = 'initialize'
		params  = {
			protocolVersion = '2025-03-26'
			capabilities    = {}
			clientInfo      = { name = 'stdio-tester', version = '1.0.0' }
		}
	})
	init_obj = json/decode init_line
	init_res = map/get init_obj 'result'
	_ = assert-eq/or 'stdio initialize protocolVersion' (map/get init_res 'protocolVersion') '2025-03-26' [e -> return e]

	notif_line = mcp/handle-jsonrpc-line mut srv (json/encode {
		jsonrpc = '2.0'
		method  = 'notifications/initialized'
	})
	_ = assert-eq/or 'stdio notification emits empty line' notif_line '' [e -> return e]

	bad_json_line = mcp/handle-jsonrpc-line mut srv '{broken-json'
	bad_json_obj = json/decode bad_json_line
	_ = assert-eq/or 'JSON-RPC -32700 parse error' (map/get (map/get bad_json_obj 'error') 'code') -32700 [e -> return e]

	no_method_line = mcp/handle-jsonrpc-line mut srv (json/encode {
		jsonrpc = '2.0'
		id      = 99
		method  = 'nonexistent/method'
	})
	no_method_obj = json/decode no_method_line
	_ = assert-eq/or 'JSON-RPC -32601 method not found' (map/get (map/get no_method_obj 'error') 'code') -32601 [e -> return e]

	bad_params_line = mcp/handle-jsonrpc-line mut srv (json/encode {
		jsonrpc = '2.0'
		id      = 100
		method  = 'tools/call'
		params  = { name = 'search_docs', arguments = {} }
	})
	bad_params_obj = json/decode bad_params_line
	_ = assert-eq/or 'JSON-RPC -32602 missing required tool param' (map/get (map/get bad_params_obj 'error') 'code') -32602 [e -> return e]

	// 3. Verify Streamable HTTP route (`mount-http` + `web/handle-request` on `/mcp`) & `McpClient`
	mut app = web/new-app
	mcp/mount-http mut app '/mcp' (build-demo-server)

	// Verify SSE GET discovery on `/mcp`
	sse_get = web/handle-request app (web/Request {
		method  = 'GET'
		path    = '/mcp'
		target  = '/mcp'
		query   = {}
		params  = {}
		headers = {}
		body    = bytes/with-cap 0
	})
	_ = assert-eq/or 'GET /mcp status 200 SSE' sse_get.status 200 [e -> return e]
	_ = assert-eq/or 'GET /mcp Mcp-Protocol-Version header' (map/get/or sse_get.headers 'Mcp-Protocol-Version' [ '' ]) '2025-03-26' [e -> return e]

	// Run full client lifecycle over `/mcp` via `web/handle-request`
	mut client = mcp/new-app-client app '/mcp'
	hs = mcp/client-initialize/or mut client [e -> return e]
	_ = assert-eq/or 'HTTP client initialize version' (map/get hs 'protocolVersion') '2025-03-26' [e -> return e]
	_ = assert-eq/or 'HTTP serverInfo.name' (map/get client.server_info 'name') 'veko-knowledge-mcp' [e -> return e]

	tools = mcp/client-list-tools/or mut client [e -> return e]
	_ = assert-eq/or 'HTTP tools/list count' (len tools) 2 [e -> return e]

	call_ok = mcp/client-call-tool/or mut client 'search_docs' { query = 'Ownership', limit = 3 } [e -> return e]
	_ = assert-eq/or 'HTTP tools/call isError=false' (map/get call_ok 'isError') false [e -> return e]
	c_items = map/get call_ok 'content'
	_ = assert-eq/or 'HTTP tools/call output text' (map/get c_items[0] 'text') 'Found 3 matches for "ownership"' [e -> return e]

	call_sum = mcp/client-call-tool/or mut client 'sum_ints' { a = 19, b = 23 } [e -> return e]
	_ = assert-eq/or 'HTTP tools/call sum_ints' (map/get (map/get call_sum 'content')[0] 'text') '42' [e -> return e]

	call_err = mcp/client-call-tool/or mut client 'search_docs' { query = 'fail' } [e -> return e]
	_ = assert-eq/or 'HTTP tools/call handler err sets isError=true' (map/get call_err 'isError') true [e -> return e]

	resources = mcp/client-list-resources/or mut client [e -> return e]
	_ = assert-eq/or 'HTTP resources/list count' (len resources) 1 [e -> return e]

	rcontents = mcp/client-read-resource/or mut client 'veko://specs/mcp' [e -> return e]
	_ = assert-true/or 'HTTP resources/read text' (str/contains? (map/get rcontents[0] 'text') '2025-03-26') [e -> return e]

	prompts = mcp/client-list-prompts/or mut client [e -> return e]
	_ = assert-eq/or 'HTTP prompts/list count' (len prompts) 1 [e -> return e]

	prompt_res = mcp/client-get-prompt/or mut client 'code_review' { module = 'ai_mcp', focus = 'JSON-RPC edge cases' } [e -> return e]
	pmsgs = map/get prompt_res 'messages'
	_ = assert-eq/or 'HTTP prompts/get message count' (len pmsgs) 1 [e -> return e]
	_ = assert-true/or 'HTTP prompts/get rendered text' (str/contains? (map/get (map/get pmsgs[0] 'content') 'text') 'JSON-RPC edge cases') [e -> return e]

	println 'ai_mcp demo: all checks passed.'
	0
]

main
`g¡!šâ�2B¹¸´æŠzÞ&9ßýþïÒ¬K”y mod.vk  Zã// packages/ai_mcp/src/mod.vk
// Model Context Protocol (MCP 2025-03-26) JSON-RPC 2.0 Server & Client for Veko.
// Provides homoiconic tool parameter JSON Schema generation, NDJSON stdio line
// dispatch, Streamable HTTP (`web/App`) mounting, and a multi-transport MCP client.

use [web, pem = codec/pem, hc = net/client]

// Negotiated MCP specification version.
pub MCP-PROTOCOL-VERSION = fn [] str [ '2025-03-26' ]

// Standard JSON-RPC 2.0 error codes.
pub ERR-PARSE-ERROR      = fn [] i64 [ -32700 ]
pub ERR-INVALID-REQUEST  = fn [] i64 [ -32600 ]
pub ERR-METHOD-NOT-FOUND = fn [] i64 [ -32601 ]
pub ERR-INVALID-PARAMS   = fn [] i64 [ -32602 ]
pub ERR-INTERNAL         = fn [] i64 [ -32603 ]

// Registered MCP tool definition and execution callback (`fn [args map] any`).
pub McpTool = struct {
	name         str
	description  str
	input_schema map
	handler      any
}

// Registered MCP resource definition and reader callback (`fn [uri str] any`).
pub McpResource = struct {
	uri         str
	name        str
	description str = ''
	mime_type   str = 'text/plain'
	reader      any
}

// Declared argument metadata for an MCP prompt template.
pub McpPromptArg = struct {
	name        str
	description str  = ''
	required    bool = true
}

// Registered MCP prompt template and builder callback (`fn [args map] any`).
pub McpPrompt = struct {
	name        str
	description str   = ''
	arguments   block = []
	builder     any
}

// Stateful MCP 2025-03-26 server holding tools, resources, and prompts.
pub McpServer = struct {
	name             str
	version          str
	instructions     str   = ''
	protocol_version str   = '2025-03-26'
	initialized      bool  = false
	tools            block = []
	resources        block = []
	prompts          block = []
}

// Stateful MCP 2025-03-26 client supporting HTTP, `web/App`, and custom transports.
pub McpClient = struct {
	name        str = 'veko-mcp-client'
	version     str = '1.0.0'
	endpoint    str = ''
	next_id     i64 = 1
	initialized bool = false
	server_info map = {}
	server_caps map = {}
	transport   any = .none
}

// Creates a new MCP server with `name`, `version`, and optional `/instructions`.
pub new-server = fn [name str, version str /instructions instr str = ''] McpServer [
	McpServer {
		name             = name
		version          = version
		instructions     = instr
		protocol_version = (MCP-PROTOCOL-VERSION)
		initialized      = false
		tools            = []
		resources        = []
		prompts          = []
	}
]

vk-type-to-json-schema = fn [vt str] str [
	low = str/lower vt
	if low == 'str' or low == 'string' [ return 'string' ]
	if low == 'i64' or low == 'int' or low == 'u8' or low == 'u16' or low == 'u32' [ return 'integer' ]
	if low == 'f64' or low == 'float' or low == 'number' [ return 'number' ]
	if low == 'bool' or low == 'boolean' [ return 'boolean' ]
	if low == 'block' or low == 'array' [ return 'array' ]
	if low == 'map' or low == 'object' [ return 'object' ]
	'string'
]

// Generates an MCP JSON Schema `inputSchema` map from a homoiconic `quote [...]` block.
//
// Example:
//   `mcp/tool-schema (quote [ query str 'Search query', limit i64 .optional 'Max rows' ])`
pub tool-schema = fn [spec_blk block] map [
	mut props = {}
	mut req_list = []
	n = len spec_blk
	mut i = 0
	while i < n [
		if (mold spec_blk[i]) == ',' [
			i = i + 1
			continue
		]
		pname = mold spec_blk[i]
		i = i + 1
		mut vtype = 'str'
		if i < n and (type-of spec_blk[i]) == .word and (mold spec_blk[i]) != ',' [
			vtype = mold spec_blk[i]
			i = i + 1
		]
		jtype = vk-type-to-json-schema vtype
		mut is_req = true
		mut desc = ''
		mut has_def = false
		mut def_val = .null
		mut enum_vals = []

		while i < n [
			tok = spec_blk[i]
			tt = type-of tok
			tm = mold tok
			if tm == ',' [
				i = i + 1
				break
			]
			if tt == .enum_sym [
				if tok == .optional [ is_req = false ]
				if tok == .required [ is_req = true ]
				i = i + 1
				continue
			]
			if tt == .str [
				desc = str/append '' tok
				i = i + 1
				continue
			]
			if tt == .block [
				enum_vals = tok
				i = i + 1
				continue
			]
			if tm == '=' and (i + 1) < n [
				has_def = true
				def_val = spec_blk[i + 1]
				is_req = false
				i = i + 2
				continue
			]
			break
		]

		mut prop = {
			type = jtype
		}
		if desc != '' [
			map/set mut prop 'description' desc
		]
		if (len enum_vals) > 0 [
			map/set mut prop 'enum' enum_vals
		]
		if has_def [
			map/set mut prop 'default' def_val
		]
		map/set mut props pname prop
		if is_req [
			push mut req_list pname
		]
	]

	mut schema = {
		type       = 'object'
		properties = props
	}
	if (len req_list) > 0 [
		map/set mut schema 'required' req_list
	]
	schema
]

// Registers a callable tool on `srv`.
pub add-tool = fn [mut srv McpServer, name str, description str, input_schema map, handler any] [
	mut ts = srv.tools
	push mut ts (McpTool {
		name         = name
		description  = description
		input_schema = input_schema
		handler      = handler
	})
	put mut srv .tools ts
	.ok
]

// Registers a readable resource URI on `srv`.
pub add-resource = fn [mut srv McpServer, uri str, name str, description str, mime_type str, reader any] [
	mut rs = srv.resources
	push mut rs (McpResource {
		uri         = uri
		name        = name
		description = description
		mime_type   = if mime_type == '' [ 'text/plain' ] else [ mime_type ]
		reader      = reader
	})
	put mut srv .resources rs
	.ok
]

// Builds a prompt argument descriptor (`McpPromptArg`).
pub prompt-arg = fn [name str, description str, required bool] McpPromptArg [
	McpPromptArg {
		name        = name
		description = description
		required    = required
	}
]

// Registers a reusable prompt template on `srv`.
pub add-prompt = fn [mut srv McpServer, name str, description str, arguments block, builder any] [
	mut ps = srv.prompts
	push mut ps (McpPrompt {
		name        = name
		description = description
		arguments   = arguments
		builder     = builder
	})
	put mut srv .prompts ps
	.ok
]

// Builds an MCP text content item (`{ type = 'text', text = ... }`).
pub text-content = fn [text str] map [
	{
		type = 'text'
		text = text
	}
]

// Builds an MCP prompt message (`{ role = ..., content = { type = 'text', text = ... } }`).
pub prompt-message = fn [role str, text str] map [
	{
		role    = role
		content = (text-content text)
	}
]

// Builds a JSON-RPC 2.0 success envelope.
pub jsonrpc-ok = fn [id any, result any] map [
	{
		jsonrpc = '2.0'
		id      = id
		result  = result
	}
]

// Builds a JSON-RPC 2.0 error envelope with `code` and `message`.
pub jsonrpc-error = fn [id any, code i64, message str] map [
	{
		jsonrpc = '2.0'
		id      = id
		error   = {
			code    = code
			message = message
		}
	}
]

// Builds a JSON-RPC 2.0 error envelope with structured `data`.
pub jsonrpc-error-data = fn [id any, code i64, message str, data any] map [
	{
		jsonrpc = '2.0'
		id      = id
		error   = {
			code    = code
			message = message
			data    = data
		}
	}
]

find-tool-idx = fn [tools block, want str] i64 [
	mut i = 0
	while i < (len tools) [
		if tools[i].name == want [ return i ]
		i = i + 1
	]
	-1
]

find-resource-idx = fn [resources block, want_uri str] i64 [
	mut i = 0
	while i < (len resources) [
		if resources[i].uri == want_uri [ return i ]
		i = i + 1
	]
	-1
]

find-prompt-idx = fn [prompts block, want str] i64 [
	mut i = 0
	while i < (len prompts) [
		if prompts[i].name == want [ return i ]
		i = i + 1
	]
	-1
]

invoke-1 = fn [f any, arg any] any [
	(f arg)
]

normalize-tool-result = fn [out any] map [
	if err? out [
		return {
			content = [(text-content (mold out))]
			isError = true
		}
	]
	tv = type-of out
	if tv == .map_val and (map/has? out 'content') [
		mut res = out
		if not (map/has? res 'isError') [
			map/set mut res 'isError' false
		]
		return res
	]
	if tv == .str [
		return {
			content = [(text-content (str/append '' out))]
			isError = false
		}
	]
	enc = json/encode/or out [ mold out ]
	{
		content = [(text-content enc)]
		isError = false
	}
]

build-capabilities = fn [srv McpServer] map [
	mut caps = {}
	if (len srv.tools) > 0 [
		map/set mut caps 'tools' { listChanged = false }
	]
	if (len srv.resources) > 0 [
		map/set mut caps 'resources' { subscribe = false, listChanged = false }
	]
	if (len srv.prompts) > 0 [
		map/set mut caps 'prompts' { listChanged = false }
	]
	caps
]

handle-single-object = fn [mut srv McpServer, msg any] any [
	if (type-of msg) != .map_val [
		return (jsonrpc-error .null (ERR-INVALID-REQUEST) 'Invalid Request: expected JSON object')
	]
	has_id = map/has? msg 'id'
	req_id = map/get/or msg 'id' [ .null ]
	jver = str/append '' (map/get/or msg 'jsonrpc' [ '' ])
	if jver != '2.0' [
		return (jsonrpc-error req_id (ERR-INVALID-REQUEST) 'Invalid Request: jsonrpc must be "2.0"')
	]
	if not (map/has? msg 'method') [
		return (jsonrpc-error req_id (ERR-INVALID-REQUEST) 'Invalid Request: missing method')
	]
	raw_m = map/get msg 'method'
	if (type-of raw_m) != .str [
		return (jsonrpc-error req_id (ERR-INVALID-REQUEST) 'Invalid Request: method must be a string')
	]
	method = str/append '' raw_m
	params = map/get/or msg 'params' [ {} ]

	// JSON-RPC 2.0 notifications omit `id` and never produce a response object.
	if not has_id [
		if method == 'notifications/initialized' [
			put mut srv .initialized true
		]
		return .none
	]

	if method != '' and (type-of params) != .map_val and params != .null [
		return (jsonrpc-error req_id (ERR-INVALID-PARAMS) 'Invalid params: expected object')
	]
	pmap = if (type-of params) == .map_val [ params ] else [ {} ]

	if method == 'initialize' [
		put mut srv .initialized true
		mut init_res = {
			protocolVersion = srv.protocol_version
			capabilities    = (build-capabilities srv)
			serverInfo      = {
				name    = srv.name
				version = srv.version
			}
		}
		if srv.instructions != '' [
			map/set mut init_res 'instructions' srv.instructions
		]
		return (jsonrpc-ok req_id init_res)
	]

	if method == 'ping' [
		return (jsonrpc-ok req_id {})
	]

	if method == 'tools/list' [
		mut tlist = []
		mut i = 0
		while i < (len srv.tools) [
			t = srv.tools[i]
			push mut tlist {
				name        = t.name
				description = t.description
				inputSchema = t.input_schema
			}
			i = i + 1
		]
		return (jsonrpc-ok req_id { tools = tlist })
	]

	if method == 'tools/call' [
		if not (map/has? pmap 'name') [
			return (jsonrpc-error req_id (ERR-INVALID-PARAMS) 'Invalid params: tools/call requires "name"')
		]
		tname = str/append '' (map/get pmap 'name')
		tidx = find-tool-idx srv.tools tname
		if tidx < 0 [
			return (jsonrpc-error req_id (ERR-INVALID-PARAMS) `Unknown tool: {tname}`)
		]
		targs_raw = map/get/or pmap 'arguments' [ {} ]
		if (type-of targs_raw) != .map_val [
			return (jsonrpc-error req_id (ERR-INVALID-PARAMS) 'Invalid params: tool "arguments" must be an object')
		]
		tool_def = srv.tools[tidx]
		// Validate required schema keys if present
		req_keys = map/get/or tool_def.input_schema 'required' [ [] ]
		mut rk = 0
		while rk < (len req_keys) [
			kname = str/append '' req_keys[rk]
			if not (map/has? targs_raw kname) [
				return (jsonrpc-error req_id (ERR-INVALID-PARAMS) `Missing required tool argument: {kname}`)
			]
			rk = rk + 1
		]
		hfn = tool_def.handler
		out = invoke-1/or hfn targs_raw [e -> e]
		return (jsonrpc-ok req_id (normalize-tool-result out))
	]

	if method == 'resources/list' [
		mut rlist = []
		mut i = 0
		while i < (len srv.resources) [
			r = srv.resources[i]
			push mut rlist {
				uri         = r.uri
				name        = r.name
				description = r.description
				mimeType    = r.mime_type
			}
			i = i + 1
		]
		return (jsonrpc-ok req_id { resources = rlist })
	]

	if method == 'resources/read' [
		if not (map/has? pmap 'uri') [
			return (jsonrpc-error req_id (ERR-INVALID-PARAMS) 'Invalid params: resources/read requires "uri"')
		]
		want_uri = str/append '' (map/get pmap 'uri')
		ridx = find-resource-idx srv.resources want_uri
		if ridx < 0 [
			return (jsonrpc-error req_id (ERR-INVALID-PARAMS) `Unknown resource URI: {want_uri}`)
		]
		res_def = srv.resources[ridx]
		rfn = res_def.reader
		val = invoke-1/or rfn want_uri [e -> e]
		if err? val [
			return (jsonrpc-error req_id (ERR-INTERNAL) (mold val))
		]
		vt = type-of val
		mut item = {
			uri      = want_uri
			mimeType = res_def.mime_type
		}
		if vt == .bytes [
			map/set mut item 'blob' (pem/b64-encode val)
		] else [
			if vt == .map_val and ((map/has? val 'text') or (map/has? val 'blob')) [
				item = val
				if not (map/has? item 'uri') [ map/set mut item 'uri' want_uri ]
				if not (map/has? item 'mimeType') [ map/set mut item 'mimeType' res_def.mime_type ]
			] else [
				txt = if vt == .str [ str/append '' val ] else [ json/encode/or val [ mold val ] ]
				map/set mut item 'text' txt
			]
		]
		return (jsonrpc-ok req_id { contents = [item] })
	]

	if method == 'prompts/list' [
		mut plist = []
		mut i = 0
		while i < (len srv.prompts) [
			p = srv.prompts[i]
			mut args_out = []
			mut ai = 0
			while ai < (len p.arguments) [
				pa = p.arguments[ai]
				push mut args_out {
					name        = pa.name
					description = pa.description
					required    = pa.required
				}
				ai = ai + 1
			]
			push mut plist {
				name        = p.name
				description = p.description
				arguments   = args_out
			}
			i = i + 1
		]
		return (jsonrpc-ok req_id { prompts = plist })
	]

	if method == 'prompts/get' [
		if not (map/has? pmap 'name') [
			return (jsonrpc-error req_id (ERR-INVALID-PARAMS) 'Invalid params: prompts/get requires "name"')
		]
		pname = str/append '' (map/get pmap 'name')
		pidx = find-prompt-idx srv.prompts pname
		if pidx < 0 [
			return (jsonrpc-error req_id (ERR-INVALID-PARAMS) `Unknown prompt: {pname}`)
		]
		pdef = srv.prompts[pidx]
		pargs = map/get/or pmap 'arguments' [ {} ]
		if (type-of pargs) != .map_val [
			return (jsonrpc-error req_id (ERR-INVALID-PARAMS) 'Invalid params: prompt "arguments" must be an object')
		]
		mut ai = 0
		while ai < (len pdef.arguments) [
			pa = pdef.arguments[ai]
			if pa.required and (not (map/has? pargs pa.name)) [
				return (jsonrpc-error req_id (ERR-INVALID-PARAMS) `Missing required prompt argument: {pa.name}`)
			]
			ai = ai + 1
		]
		bfn = pdef.builder
		built = invoke-1/or bfn pargs [e -> e]
		if err? built [
			return (jsonrpc-error req_id (ERR-INTERNAL) (mold built))
		]
		bt = type-of built
		if bt == .map_val and (map/has? built 'messages') [
			mut out_m = built
			if not (map/has? out_m 'description') [
				map/set mut out_m 'description' pdef.description
			]
			return (jsonrpc-ok req_id out_m)
		]
		msgs = if bt == .block [
			built
		] else [
			[(prompt-message 'user' (if bt == .str [ str/append '' built ] else [ mold built ]))]
		]
		return (jsonrpc-ok req_id {
			description = pdef.description
			messages    = msgs
		})
	]

	jsonrpc-error req_id (ERR-METHOD-NOT-FOUND) `Method not found: {method}`
]

// Dispatches a decoded JSON-RPC 2.0 request or batch against `srv`.
// Returns a response `map`, batch `block`, or `.none` for notifications.
pub handle-message = fn [mut srv McpServer, msg any] any [
	tv = type-of msg
	if tv == .block [
		if (len msg) == 0 [
			return (jsonrpc-error .null (ERR-INVALID-REQUEST) 'Invalid Request: empty batch')
		]
		mut resps = []
		mut i = 0
		while i < (len msg) [
			r = handle-single-object mut srv msg[i]
			if r != .none [
				push mut resps r
			]
			i = i + 1
		]
		if (len resps) == 0 [ return .none ]
		return resps
	]
	handle-single-object mut srv msg
]

// Dispatches one newline-delimited JSON-RPC 2.0 line (MCP stdio transport).
// Returns a single-line JSON response string, or `''` for empty lines and notifications.
pub handle-jsonrpc-line = fn [mut srv McpServer, line str] str [
	trimmed = str/trim line
	if trimmed == '' [ return '' ]
	parsed = json/decode/or trimmed [
		err_obj = jsonrpc-error .null (ERR-PARSE-ERROR) 'Parse error: invalid JSON'
		return (json/encode err_obj)
	]
	resp = handle-message mut srv parsed
	if resp == .none [ return '' ]
	json/encode resp
]

// Mounts `srv` onto `app` at `route_path` using the MCP 2025-03-26 Streamable HTTP transport.
// `POST route_path` processes JSON-RPC 2.0 requests (`200 OK` JSON) and notifications (`202 Accepted`);
// `GET route_path` serves an SSE discovery stream (`text/event-stream`).
pub mount-http = fn [mut app web/App, route_path str, srv McpServer] [
	web/post mut app route_path fn [req web/Request] web/Response [
		raw_txt = str/trim (bytes/to-str req.body)
		if raw_txt == '' [
			err_empty = jsonrpc-error .null (ERR-PARSE-ERROR) 'Parse error: empty request body'
			mut r_emp = web/json-resp 200 err_empty
			mut h_emp = r_emp.headers
			map/set mut h_emp 'Mcp-Protocol-Version' (MCP-PROTOCOL-VERSION)
			put mut r_emp .headers h_emp
			return r_emp
		]
		decoded = json/decode/or raw_txt [
			err_parse = jsonrpc-error .null (ERR-PARSE-ERROR) 'Parse error: malformed JSON'
			mut r_bad = web/json-resp 200 err_parse
			mut h_bad = r_bad.headers
			map/set mut h_bad 'Mcp-Protocol-Version' (MCP-PROTOCOL-VERSION)
			put mut r_bad .headers h_bad
			return r_bad
		]
		mut local_srv = srv
		out = handle-message mut local_srv decoded
		if out == .none [
			mut hdrs_202 = {}
			map/set mut hdrs_202 'Mcp-Protocol-Version' (MCP-PROTOCOL-VERSION)
			return (web/Response {
				status  = 202
				reason  = 'Accepted'
				headers = hdrs_202
				body    = bytes/with-cap 0
			})
		]
		mut resp = web/json-resp 200 out
		mut hdrs = resp.headers
		map/set mut hdrs 'Mcp-Protocol-Version' (MCP-PROTOCOL-VERSION)
		put mut resp .headers hdrs
		resp
	]

	web/get mut app route_path fn [_req web/Request] web/Response [
		info_json = json/encode {
			protocolVersion = srv.protocol_version
			endpoint        = route_path
			serverInfo      = { name = srv.name, version = srv.version }
		}
		mut resp = web/sse-resp (web/sse-event 'endpoint' info_json '1')
		mut hdrs = resp.headers
		map/set mut hdrs 'Mcp-Protocol-Version' (MCP-PROTOCOL-VERSION)
		put mut resp .headers hdrs
		resp
	]
	.ok
]

// --- MCP 2025-03-26 Client ---

// Creates an MCP client backed by a custom JSON-RPC line/HTTP transport (`fn [req_json str] str`).
pub new-custom-client = fn [endpoint str, transport_fn any] McpClient [
	McpClient {
		endpoint  = endpoint
		transport = transport_fn
	}
]

// Creates an MCP Streamable HTTP client sending `POST` JSON-RPC 2.0 requests to `endpoint_url`.
pub new-http-client = fn [endpoint_url str /headers extra_headers map = {}] McpClient [
	McpClient {
		endpoint  = endpoint_url
		transport = fn [payload_json str] any [
			mut hdrs = {
				'Content-Type'         = 'application/json'
				'Accept'               = 'application/json, text/event-stream'
				'Mcp-Protocol-Version' = (MCP-PROTOCOL-VERSION)
			}
			ks = map/keys extra_headers
			mut i = 0
			while i < (len ks) [
				k = str/append '' ks[i]
				map/set mut hdrs k (str/append '' (map/get extra_headers k))
				i = i + 1
			]
			opts = hc/RequestOpts { headers = hdrs, timeout = 15s }
			resp = hc/post/or endpoint_url (bytes/from-str payload_json) opts [e -> return e]
			if resp.status == 202 [ return '' ]
			if resp.status < 200 or resp.status >= 300 [
				return (err `ai_mcp: HTTP {mold resp.status} from {endpoint_url}`)
			]
			bytes/to-str resp.body
		]
	}
]

// Creates an in-process MCP client dispatching Streamable HTTP requests directly against `app` at `route_path`.
pub new-app-client = fn [app web/App, route_path str] McpClient [
	McpClient {
		endpoint  = route_path
		transport = fn [payload_json str] any [
			req = web/Request {
				method  = 'POST'
				path    = route_path
				target  = route_path
				query   = {}
				params  = {}
				headers = {
					'Content-Type'         = 'application/json'
					'Mcp-Protocol-Version' = (MCP-PROTOCOL-VERSION)
				}
				body    = (bytes/from-str payload_json)
			}
			resp = web/handle-request app req
			if resp.status == 202 [ return '' ]
			if resp.status < 200 or resp.status >= 300 [
				return (err `ai_mcp: app HTTP {mold resp.status}`)
			]
			bytes/to-str resp.body
		]
	}
]

client-rpc = fn [mut client McpClient, method str, params map] any [
	id = client.next_id
	put mut client .next_id (id + 1)
	req_msg = {
		jsonrpc = '2.0'
		id      = id
		method  = method
		params  = params
	}
	raw_req = json/encode req_msg
	tfn = client.transport
	raw_resp = (tfn raw_req)
	if err? raw_resp [ return raw_resp ]
	resp_obj = json/decode/or (str/append '' raw_resp) [
		return (err 'ai_mcp: invalid JSON response from server')
	]
	if (type-of resp_obj) != .map_val [
		return (err 'ai_mcp: expected JSON object response')
	]
	if map/has? resp_obj 'error' [
		eobj = map/get resp_obj 'error'
		ecode = map/get/or eobj 'code' [ -1 ]
		emsg = str/append '' (map/get/or eobj 'message' [ 'MCP error' ])
		return (err `ai_mcp rpc error ({mold ecode}): {emsg}`)
	]
	map/get/or resp_obj 'result' [ {} ]
]

client-notify = fn [client McpClient, method str, params map] enum [
	notif = {
		jsonrpc = '2.0'
		method  = method
		params  = params
	}
	tfn = client.transport
	out = (tfn (json/encode notif))
	if err? out [ return out ]
	.ok
]

// Performs the MCP `initialize` handshake + `notifications/initialized` notification.
pub client-initialize = fn [mut client McpClient] any [
	res = client-rpc/or mut client 'initialize' {
		protocolVersion = (MCP-PROTOCOL-VERSION)
		capabilities    = {}
		clientInfo      = {
			name    = client.name
			version = client.version
		}
	} [e -> return e]

	_ = client-notify client 'notifications/initialized' {}
	put mut client .initialized true
	put mut client .server_info (map/get/or res 'serverInfo' [ {} ])
	put mut client .server_caps (map/get/or res 'capabilities' [ {} ])
	res
]

// Sends a JSON-RPC `ping` request to verify liveness.
pub client-ping = fn [mut client McpClient] any [
	client-rpc mut client 'ping' {}
]

// Lists all tools exposed by the connected MCP server.
pub client-list-tools = fn [mut client McpClient] any [
	res = client-rpc/or mut client 'tools/list' {} [e -> return e]
	map/get/or res 'tools' [ [] ]
]

// Invokes a named MCP tool with `arguments` and returns `{ content = [...], isError = ... }`.
pub client-call-tool = fn [mut client McpClient, name str, arguments map] any [
	client-rpc mut client 'tools/call' {
		name      = name
		arguments = arguments
	}
]

// Lists all resources exposed by the connected MCP server.
pub client-list-resources = fn [mut client McpClient] any [
	res = client-rpc/or mut client 'resources/list' {} [e -> return e]
	map/get/or res 'resources' [ [] ]
]

// Reads a resource `uri` from the connected MCP server and returns its `contents` block.
pub client-read-resource = fn [mut client McpClient, uri str] any [
	res = client-rpc/or mut client 'resources/read' { uri = uri } [e -> return e]
	map/get/or res 'contents' [ [] ]
]

// Lists all prompt templates exposed by the connected MCP server.
pub client-list-prompts = fn [mut client McpClient] any [
	res = client-rpc/or mut client 'prompts/list' {} [e -> return e]
	map/get/or res 'prompts' [ [] ]
]

// Renders a named prompt template with `arguments` and returns `{ description, messages }`.
pub client-get-prompt = fn [mut client McpClient, name str, arguments map] any [
	client-rpc mut client 'prompts/get' {
		name      = name
		arguments = arguments
	}
]
Õ/™þç`§¾G`†cžS¼IÐùz©ÕY`0�¤+ÐRø`0�ïÖN¿ª;(=´Ï2|VèŸÓ%�Hö`n±   '@`tØh¡ÔæB]ˆ|¬Ã3L$šÀGº�N-÷+p   @mx#‡®{À`÷Èë'xõæw0œgÒWQ5–O1tûc›£ucPC˜993A˜s¡¢çO°u@‡4—k{œ
