Sync upstream updates: MCP request errors and origin checks, Gemini classification and AI streaming fixes
Merged
BI
19h ago+3268+3268+0123456789012345678901234567890123456789-574-574-012345678901234567890123456789
Upstream Updates
- laravel/mcp@b82ad51d74 — Declare the never return type on the throwing closure in the OAuth advertisement-probe test. The other closures and fixtures upstream typed already had native return types.
- laravel/mcp#391, laravel/mcp#397 — Show a header value that isn't printable in its base64 form in mismatch messages and the legacy version error, instead of replacing its invalid bytes in the response. Ignore surrounding whitespace when comparing header values, check a legacy request's version header against the versions the server supports, and include the requested URI in a missing resource's error. Stateless requests treat initialize and ping as unknown methods.
- laravel/mcp#395 — Return precise JSON-RPC errors for malformed requests. Hypervel already rejected most malformed bodies and params; it now uses upstream's Invalid Request message for a body that isn't a JSON object, rejects a top-level array, and validates {} and objects with numeric member names as requests. A result that can't be encoded is reported and answered with an internal error that shows the encoder message only in debug mode, a notification that can't be encoded is dropped, and errors without an ID take the request's ID. JsonRpcRequest::validate() is available for custom JSON-RPC methods.
- laravel/mcp#392 — Stop following redirects in the MCP HTTP client transport. Hypervel stripped custom headers on cross-origin redirects, but the redirected request still sent its body to the new destination, including internal addresses. A redirect now fails with a TransportException naming its status, so clients use the server's final URL. The OAuth discovery probe keeps its own redirect handling.
- laravel/mcp#394 — Check the Origin header on the GET and DELETE MCP routes as well as POST, and answer a rejected origin with a JSON-RPC 403 error. '*' allows every origin, mcp.allowed_origins accepts a string or a list, and configured origins may end with a slash. Hypervel keeps stricter rules: the header and each configured entry must be a bare origin, so an entry with a path doesn't trust every app on its host, and loopback origins must be configured like any other, because a local web app isn't necessarily one the server operator trusts.
- laravel/mcp#396, laravel/mcp#397 — Add upstream's conformance tools for custom headers, JSON Schema 2020-12, logging and streaming elicitation, and pin the conformance runner to 0.2.0-alpha.12 so results don't shift with new suite releases. The conformance client selects its tool calls as upstream does, and the baseline drops the JSON Schema 2020-12 and header validation checks, which now pass.
- laravel/ai#1192 — Assemble streamed tool calls from OpenAI-compatible servers that send deltas without an index. A delta without an index continues the last call unless it names a new one. Hypervel already treated a "stop" finish that carries tool calls as a tool turn.
- laravel/ai#1215 — Throw InvalidApiKeyException, naming the provider and saying the key is missing or invalid, when a provider rejects the API key. Gemini and xAI report a rejected key with their own statuses and messages, so their gateways use provider-specific checks. The exception doesn't trigger failover.
- laravel/ai#1208, laravel/docs#11439 — Broadcast AI stream events under their event type, and provider stream errors as "error", so Echo listeners can subscribe by name. A failed broadcastOnQueue operation still broadcasts "stream_failed". The docs list the event names with an Echo example.
- laravel/ai#1212 — Send OpenAI custom voice IDs (voice_...) as a voice object, as the speech API requires.
- laravel/ai#1214 — Emit one citation per URL for Anthropic web search results and fetched pages in streams, and stop reporting uncited search results as citations in buffered responses.
- laravel/ai#1231 — Add Gemini classification through its Decisions API, with gemini-decision-1 as the default model and image attachments, including images already stored with Gemini. Shared classification gains payload and usage hooks, and declared score levels take precedence over a returned legend. Gemini keeps numeric choice labels as JSON object members, as the other providers already did, and the classification docs now list Gemini.
- laravel/ai#1217 — Make gpt-transcribe OpenAI's default transcription model. gpt-transcribe models reject diarization and send their languages as languages[] fields, and the Groq and OpenRouter diarization errors no longer suggest OpenAI. The diarization docs example names gpt-4o-transcribe-diarize, since the default model would reject it.
- laravel/ai#1219 — Send Anthropic tools marked #[Strict] with strict and additionalProperties: false when native structured output is enabled, moving schema constraints Anthropic doesn't support into descriptions.
- laravel/ai#1220 — Merge provider options set on document and image attachments, such as cache control, into their Anthropic content blocks. OpenAI already forwarded them.
- laravel/ai#1216 — Decode structured output when a model's code fence is never closed, or is left with unpaired backticks on either side of the JSON.
- laravel/ai#1222 — Store the text of every step of a prompted response in the database conversation store, so a turn keeps text the model wrote before calling a tool. Steps are joined the way streamed text is: continuation steps run together and a tool call starts a new paragraph. Streamed and structured responses keep their own text. Unlike upstream, resuming a paused turn appends its text to the paused text instead of rejoining every step, so text a response carries without steps, such as text a resumePausedRow() override supplies, is kept.
- laravel/ai#1218 — Keep every tool call of a streamed Ollama reply. Ollama sends each call complete, and calls streamed in separate chunks can share an index, so Hypervel's merging by index folded distinct calls into one.
Additional Hypervel changes
- Check the shape of MCP completion request params before resolving the reference. The validator skips type rules for blank strings, so upstream's rules let a blank ref or context.arguments reach typed parameters and fail with a TypeError.
- Treat initialize and ping as unknown on stateless MCP requests even when an application replaces their handlers. Upstream checks the handler class instead of the method name.
- Report an MCP 403 that carries a JSON-RPC error and no authentication challenge, such as an Origin rejection, as a protocol error. Upstream treats every 403 as an authorization requirement, so tools(default: ...) silently returned its fallback.
- Throw a TransportException when an MCP server rejects a notification, with the server's message when the body carries a JSON-RPC error, and keep the session on an ordinary notification rejection. Upstream queued a JSON-RPC rejection instead of reporting it, and cleared the session on any other rejection.
- Continue an earlier OpenAI-compatible tool call when an index-less delta carries its id. Upstream only compared the id with the last call, so an interleaved fragment of the first of two parallel calls lost its arguments and produced an extra call.
- Send classification questions as a JSON object when their names are numeric, and leave out empty Boolean criteria instead of sending a JSON list. Numeric names sent the questions as a list to Gemini, TypeSafe and OpenRouter.
- Throw a JsonException when classification state can't be encoded in the Gemini and OpenAI gateways, instead of failing with a TypeError.
- Keep the failover exception for a provider error whose body isn't JSON, such as an HTML error page, when the application's default JSON decoding flags include JSON_THROW_ON_ERROR. Failover handling, including the xAI and Gemini API key checks, now reads error bodies without throwing.
- Keep streamed Anthropic citations on their text blocks, as buffered responses do, so a step's citations and the content replayed on a later turn include them.
- Document strict tool and structured-output schemas: which providers enforce them, OpenAI's requirement that every property is required, so a property that may have no value is also nullable, and Anthropic moving unsupported constraints into descriptions. Upstream has no docs for the Strict attribute.
[!NOTE]
Sync upstream: MCP request validation and origin checks, Gemini classification, AI streaming fixes
- Adds Gemini classification support via
GeminiClassificationGateway and GeminiProvider (default model gemini-decision-1), mapping Boolean, Choice, and Score questions plus text and inline-image inputs.
- Adds
ValidateOrigin middleware for the MCP web endpoint: only the app.url origin, configured mcp.allowed_origins entries, or * are allowed; loopback origins are no longer trusted implicitly. Rejections return JSON-RPC errors with HTTP 403.
- Hardens MCP request handling:
JsonRpcRequest.validate returns validated data or an invalid-params error; Server rejects non-object JSON bodies, drops unencodable notifications, and sends internal-error responses when encoding fails.
HttpTransport.send no longer follows redirects and throws TransportException for them; header mismatch errors trim whitespace and escape control characters.
- Fixes AI streaming: OpenAI-compatible tool-call deltas without an index are assigned an inferred index; Ollama tool calls map per chunk; Anthropic dedupes citation events per URL; structured output decoding recovers JSON from unmatched code fences; HTTP 401 responses now raise
InvalidApiKeyException.
- OpenAI transcription defaults to
gpt-transcribe, which rejects diarization and sends languages as languages[] parts; assistant-message storage in DatabaseConversationStore derives content from grouped steps.
- Risk: MCP clients relying on automatic loopback-origin acceptance must now list those origins in
mcp.allowed_origins (mcp.php); ReadResource.handle includes URI error data only for non-empty string URIs; OpenAiProvider.defaultTranscriptionModel changes the fallback from gpt-4o-transcribe-diarize to gpt-transcribe, which does not support diarization.
📊 Macroscope summarized 1944d2d. 52 files reviewed, 7 issues evaluated, 1 issue filtered, 6 comments posted
🗂️ Filtered Issues
src/ai/src/Gateway/Gemini/GeminiClassificationGateway.php — 0 comments posted, 1 evaluated, 1 filtered
- line 108: Omit Boolean criteria after filtering out absent descriptions.
Boolean validates the keys but accepts ['true' => null] at runtime. For that input, the outer condition sees a nonempty array, the inner filter produces [], and the outer filter keeps it. The resulting payload contains "criteria":[] instead of omitting criteria as it does for a Boolean question with no descriptions. [ Out of scope (post-validation triage) ]
Summary by CodeRabbit
-
New Features
- Added Gemini support for AI-powered classification, including image attachments.
- Improved handling of invalid API keys with clearer provider-specific errors.
- Added stricter tool schemas, more reliable streaming tool calls, and improved conversation text storage.
- Expanded MCP conformance coverage and request validation.
-
Bug Fixes
- Improved MCP origin and redirect handling, error responses, and input validation.
- Reduced duplicate citations and improved recovery of structured output from incomplete formatting.
- Updated transcription language handling and custom voice ID support.
-
Documentation
- Clarified MCP origin requirements, redirect behavior, and AI provider capabilities.