Skip to content

[Server] Allow context propagation into handler fibers - #670

Open
bbdu3 wants to merge 1 commit into
modelcontextprotocol:mainfrom
bbdu3:codex/fiber-context-factory
Open

bbdu3 wants to merge 1 commit into
modelcontextprotocol:mainfrom
bbdu3:codex/fiber-context-factory

Conversation

@bbdu3

@bbdu3 bbdu3 commented Nov 5, 2026 •

Copy link
Copy Markdown

Summary

Add an optional integration point for propagating execution context into SDK-managed handler fibers.

With OpenTelemetry’s default fiber-bound storage, accessing context inside an uninitialized handler fiber raises a warning. When an application converts warnings into exceptions, the request fails with -32603. This fix allows applications to configure context propagation explicitly; it does not enable OpenTelemetry integration automatically.

Fixes #583

Changed

  • Add FiberFactoryInterface and Builder::setFiberFactory(), wired into Protocol and StatelessProtocol, including buildStateless().
  • Invoke the factory in the parent context and require an unstarted fiber that preserves the callback’s return value, exceptions and suspensions.
  • Document an OpenTelemetry implementation that captures the parent context, activates it inside the handler fiber and detaches it in finally. Default fiber-bound storage retains the context across suspension and resumption, avoiding additional lifecycle hooks at each start() or resume().
  • Preserve existing behavior when no factory is configured, with no additional package dependency or protocol changes.

PR #616 addresses #615 by coordinating fiber execution with an external event loop. This PR addresses context propagation and leaves scheduling unchanged. Both touch handler-fiber creation, so combining them may require adapting the factory’s integration point; their combined implementation has not been tested.

Test

  • Focused regression suite: 250 tests passed, including 16 new cases covering both protocol eras, buildStateless(), HTTP and stdio, interleaved requests, suspension/resumption, handler exceptions, and cleanup when suspended fibers are discarded.
  • OpenTelemetry reproduction: an isolated local probe using open-telemetry/context 1.5.0 passed 12 before/after scenarios with warnings promoted to exceptions. The default configuration reproduced the reported failure; the configured factory preserved context and completed cleanup without those warnings.
  • Static analysis and documentation: PHPStan, PHP CS Fixer checks on changed PHP files, and the strict documentation build passed.

Signed-off-by: bbdu3 <ergouyang854@gamil.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Server] Handler fibers give integrations no hook to carry OpenTelemetry's context

1 participant