-
Notifications
You must be signed in to change notification settings - Fork 796
Add IMcpTaskExecutor for delegating task execution to an external runtime #1843
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
trey-herrington
wants to merge
7
commits into
modelcontextprotocol:main
Choose a base branch
from
trey-herrington:task-executor-extension-point
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
eecc392
Add IMcpTaskExecutor with an execution context for task delegation
trey-herrington 6f7cd02
Route WithTasks execution through IMcpTaskExecutor
trey-herrington e01df3c
Add tests for custom task executors
trey-herrington cf81ad4
Document delegating task execution to an external runtime
trey-herrington 0d70daf
Resolve task executors from the execution scope and record start fail…
trey-herrington a1b4931
Clarify the task executor boundary contract in docs
trey-herrington 37b1165
Make McpTaskExecutionContext pipeline start and disposal atomic
trey-herrington File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
51 changes: 51 additions & 0 deletions
51
src/ModelContextProtocol.Extensions.Tasks/Server/IMcpTaskExecutor.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| using ModelContextProtocol.Protocol; | ||
| using ModelContextProtocol.Server; | ||
|
|
||
| namespace ModelContextProtocol.Extensions.Tasks; | ||
|
|
||
| /// <summary> | ||
| /// Executes a task created by the Tasks extension after the task record has been | ||
| /// durably created in the <see cref="IMcpTaskStore"/>. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// By default, tasks execute in-process via the .NET thread pool. Registering a custom | ||
| /// executor delegates execution to an external system such as Temporal, Orleans, Hangfire, | ||
| /// or a distributed queue. The executor is invoked once per task, after the task record is | ||
| /// created and the execution context is fully wired. | ||
| /// </para> | ||
| /// <para> | ||
| /// <see cref="StartAsync"/> must return only after execution has been durably started | ||
| /// (e.g., the external runtime has accepted the job), mirroring the durability requirement | ||
| /// SEP-2663 §306 places on <see cref="IMcpTaskStore.CreateTaskAsync"/>. It must not wait | ||
| /// for the task to complete; completion is recorded in the store by whichever system | ||
| /// performs the execution. | ||
| /// </para> | ||
| /// <para> | ||
| /// If <see cref="StartAsync"/> throws, the exception is not returned as an error from the | ||
| /// original <c>tools/call</c>: that call still succeeds with <see cref="CreateTaskResult"/>, | ||
| /// the task is marked failed via <see cref="IMcpTaskStore.SetFailedAsync"/>, and the client | ||
| /// discovers the failure on its first poll. After a successful <see cref="StartAsync"/>, | ||
| /// the SDK no longer tracks the task; the store is the single source of truth for its state. | ||
| /// </para> | ||
| /// <para> | ||
| /// See the <see href="https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/seps/2663-tasks-extension.md">SEP-2663</see> | ||
| /// specification for details on the tasks extension. | ||
| /// </para> | ||
| /// </remarks> | ||
| public interface IMcpTaskExecutor | ||
| { | ||
| /// <summary> | ||
| /// Starts execution of a task. | ||
| /// </summary> | ||
| /// <param name="context"> | ||
| /// The execution context for the task, providing the task identity, the matched tool | ||
| /// request bound to a fresh execution scope, and a helper for running the normal tool | ||
| /// invocation pipeline locally. | ||
| /// </param> | ||
| /// <param name="cancellationToken"> | ||
| /// A token that fires when the task is cancelled via <c>tasks/cancel</c>. | ||
| /// </param> | ||
| /// <returns>A <see cref="ValueTask"/> that completes when execution has been durably started.</returns> | ||
| ValueTask StartAsync(McpTaskExecutionContext context, CancellationToken cancellationToken); | ||
| } |
118 changes: 118 additions & 0 deletions
118
src/ModelContextProtocol.Extensions.Tasks/Server/McpTaskExecutionContext.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| using ModelContextProtocol.Protocol; | ||
| using ModelContextProtocol.Server; | ||
|
|
||
| namespace ModelContextProtocol.Extensions.Tasks; | ||
|
|
||
| /// <summary> | ||
| /// The execution context handed to an <see cref="IMcpTaskExecutor"/> when a task starts. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// The context owns the request-scoped services and the cancellation registration for task | ||
| /// execution. Executors that run the tool locally via <see cref="RunToolPipelineAsync"/> | ||
| /// never dispose anything explicitly; the context releases its resources when the pipeline | ||
| /// completes. Executors that hand execution off to an external system should extract what | ||
| /// they need from <see cref="Request"/> and then call <see cref="DisposeAsync"/> once the | ||
| /// scope-bound services are no longer needed. | ||
| /// </para> | ||
| /// <para> | ||
| /// <see cref="Request"/> carries a server whose outgoing requests (elicitation, sampling) | ||
| /// are intercepted and routed through the task's pending input requests, so responses | ||
| /// submitted via <c>tasks/update</c> are delivered even when a different server instance | ||
| /// serves the polling client. | ||
| /// </para> | ||
| /// <para> | ||
| /// <see cref="RunToolPipelineAsync"/> and <see cref="DisposeAsync"/> coordinate through an | ||
| /// atomic state transition: concurrent callers cannot both win, so the pipeline runs at most | ||
| /// once and disposal cannot race with it. Every caller but the winner observes the context | ||
| /// as disposed. | ||
| /// </para> | ||
| /// </remarks> | ||
| public sealed class McpTaskExecutionContext : IAsyncDisposable | ||
| { | ||
| private readonly Func<RequestContext<CallToolRequestParams>, CancellationToken, Task> _pipelineRunner; | ||
| private readonly Func<Task> _disposer; | ||
| private int _disposed; | ||
|
|
||
| internal McpTaskExecutionContext( | ||
| McpTaskInfo taskInfo, | ||
| RequestContext<CallToolRequestParams> request, | ||
| CancellationToken cancellation, | ||
| Func<RequestContext<CallToolRequestParams>, CancellationToken, Task> pipelineRunner, | ||
| Func<Task> disposer) | ||
| { | ||
| TaskInfo = taskInfo; | ||
| Request = request; | ||
| CancellationToken = cancellation; | ||
| _pipelineRunner = pipelineRunner; | ||
| _disposer = disposer; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Gets the unique identifier of the created task. | ||
| /// </summary> | ||
| public string TaskId => TaskInfo.TaskId; | ||
|
|
||
| /// <summary> | ||
| /// Gets the store record for the created task, with an initial status of | ||
| /// <see cref="McpTaskStatus.Working"/>. | ||
| /// </summary> | ||
| public McpTaskInfo TaskInfo { get; } | ||
|
|
||
| /// <summary> | ||
| /// Gets the matched tool request, bound to the task's execution scope, with the task | ||
| /// outgoing-request interceptor already attached. | ||
| /// </summary> | ||
| public RequestContext<CallToolRequestParams> Request { get; } | ||
|
|
||
| /// <summary> | ||
| /// Gets a token that fires when the task is cancelled via <c>tasks/cancel</c>. | ||
| /// </summary> | ||
| public CancellationToken CancellationToken { get; } | ||
|
|
||
| /// <summary> | ||
| /// Runs the normal tool invocation pipeline (the remaining request filters and the tool | ||
| /// itself), records the outcome in the task store, and releases the context's resources. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// Use this when the executor wants the tool to run locally, preserving the behavior of | ||
| /// <c>WithTasks</c> without a custom executor. Outcomes — including cancellation, protocol | ||
| /// errors, and unhandled exceptions — are recorded in the store by this call; it does not | ||
| /// rethrow them. | ||
| /// </para> | ||
| /// <para> | ||
| /// After calling this method, the executor must not use <see cref="Request"/> again, and | ||
| /// <see cref="DisposeAsync"/> becomes a no-op. | ||
| /// </para> | ||
| /// </remarks> | ||
| /// <param name="cancellationToken">A token to cancel pipeline execution.</param> | ||
| public async ValueTask RunToolPipelineAsync(CancellationToken cancellationToken) | ||
| { | ||
| if (Interlocked.CompareExchange(ref _disposed, 1, 0) != 0) | ||
| { | ||
| throw new ObjectDisposedException(nameof(McpTaskExecutionContext)); | ||
| } | ||
|
|
||
| await _pipelineRunner(Request, cancellationToken).ConfigureAwait(false); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Releases the context's resources: the request-scoped services of the execution scope | ||
| /// and the cancellation registration for the task. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Executors that hand execution off to an external system call this once they no longer | ||
| /// need <see cref="Request"/>. It is called automatically when | ||
| /// <see cref="RunToolPipelineAsync"/> completes; calling it afterwards is a no-op. | ||
| /// </remarks> | ||
| public async ValueTask DisposeAsync() | ||
| { | ||
| if (Interlocked.CompareExchange(ref _disposed, 1, 0) != 0) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| await _disposer().ConfigureAwait(false); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.