Table of Contents

Class InMemoryMcpTaskStore

Namespace
ModelContextProtocol
Assembly
ModelContextProtocol.Core.dll

Provides an in-memory implementation of IMcpTaskStore for development and testing.

[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public sealed class InMemoryMcpTaskStore : IMcpTaskStore, IDisposable
Inheritance
InMemoryMcpTaskStore
Implements
Inherited Members

Remarks

This implementation uses thread-safe concurrent collections and is suitable for single-server scenarios and testing. It is not recommended for production multi-server deployments as tasks are stored only in memory and are lost on server restart.

Features:

  • Thread-safe operations using ConcurrentDictionary<TKey, TValue>
  • Automatic TTL-based cleanup via background task
  • Session-based isolation when sessionId is provided
  • Configurable default TTL and maximum TTL limits

Constructors

InMemoryMcpTaskStore(TimeSpan?, TimeSpan?, TimeSpan?, TimeSpan?, int, int?, int?)

Initializes a new instance of the InMemoryMcpTaskStore class.

public InMemoryMcpTaskStore(TimeSpan? defaultTtl = null, TimeSpan? maxTtl = null, TimeSpan? pollInterval = null, TimeSpan? cleanupInterval = null, int pageSize = 100, int? maxTasks = null, int? maxTasksPerSession = null)

Parameters

defaultTtl TimeSpan?

Default TTL to use when task creation does not specify a TTL. Null means unlimited.

maxTtl TimeSpan?

Maximum TTL allowed. If a task requests a longer TTL, it will be capped to this value. Null means no maximum limit.

pollInterval TimeSpan?

Advertised polling interval for tasks. Default is 1 second. This value is used when creating new tasks to indicate how frequently clients should poll for updates.

cleanupInterval TimeSpan?

Interval for running background cleanup of expired tasks. Default is 1 minute. Pass InfiniteTimeSpan to disable automatic cleanup.

pageSize int

Maximum number of tasks to return per page in ListTasksAsync(string?, string?, CancellationToken). Default is 100.

maxTasks int?

Maximum number of tasks allowed in the store globally. Null means unlimited. When the limit is reached, CreateTaskAsync(McpTaskMetadata, RequestId, JsonRpcRequest, string?, CancellationToken) will throw InvalidOperationException.

maxTasksPerSession int?

Maximum number of tasks allowed per session. Null means unlimited. When the limit is reached for a session, CreateTaskAsync(McpTaskMetadata, RequestId, JsonRpcRequest, string?, CancellationToken) will throw InvalidOperationException.

Methods

CancelTaskAsync(string, string?, CancellationToken)

Attempts to cancel a task, transitioning it to Cancelled status.

public Task<McpTask> CancelTaskAsync(string taskId, string? sessionId = null, CancellationToken cancellationToken = default)

Parameters

taskId string

The unique identifier of the task to cancel.

sessionId string

Optional session identifier for access control.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task<McpTask>

The updated McpTask. If the task is already in a terminal state (Completed, Failed, or Cancelled), the task is returned unchanged.

Remarks

This method must be idempotent. If called on a task that is already in a terminal state, it returns the current task without error. This behavior differs from the MCP specification but ensures idempotency and avoids race conditions between cancellation and task completion.

For tasks not in a terminal state, the implementation should attempt to stop the underlying operation and transition the task to Cancelled status before returning.

CreateTaskAsync(McpTaskMetadata, RequestId, JsonRpcRequest, string?, CancellationToken)

Creates a new task for tracking an asynchronous operation.

public Task<McpTask> CreateTaskAsync(McpTaskMetadata taskParams, RequestId requestId, JsonRpcRequest request, string? sessionId = null, CancellationToken cancellationToken = default)

Parameters

taskParams McpTaskMetadata

Metadata for the task, including requested TTL.

requestId RequestId

The JSON-RPC request ID that initiated this task.

request JsonRpcRequest

The original JSON-RPC request that triggered task creation.

sessionId string

Optional session identifier for multi-session isolation.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task<McpTask>

A new McpTask with a unique task ID, initial status of Working, and the actual TTL that will be used (which may differ from the requested TTL).

Remarks

Implementations must generate a unique task ID and set the CreatedAt and LastUpdatedAt timestamps. The implementation may override the requested TTL to enforce storage limits.

Dispose()

Disposes the task store and stops background cleanup.

public void Dispose()

GetTaskAsync(string, string?, CancellationToken)

Retrieves a task by its unique identifier.

public Task<McpTask?> GetTaskAsync(string taskId, string? sessionId = null, CancellationToken cancellationToken = default)

Parameters

taskId string

The unique identifier of the task to retrieve.

sessionId string

Optional session identifier for access control.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task<McpTask>

The McpTask if found and accessible, otherwise null.

Remarks

Returns null if the task does not exist or if session-based access control denies access.

GetTaskResultAsync(string, string?, CancellationToken)

Retrieves the stored result of a completed or failed task.

public Task<JsonElement> GetTaskResultAsync(string taskId, string? sessionId = null, CancellationToken cancellationToken = default)

Parameters

taskId string

The unique identifier of the task.

sessionId string

Optional session identifier for access control.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task<JsonElement>

The stored operation result as a JSON element.

Remarks

This method should only be called on tasks in terminal states (Completed or Failed). The result contains the JSON representation of the original operation result (e.g., CallToolResult for tools/call).

ListTasksAsync(string?, string?, CancellationToken)

Lists tasks with pagination support.

public Task<ListTasksResult> ListTasksAsync(string? cursor = null, string? sessionId = null, CancellationToken cancellationToken = default)

Parameters

cursor string

Optional cursor for pagination, from a previous call's nextCursor value.

sessionId string

Optional session identifier for filtering tasks by session.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task<ListTasksResult>

A ListTasksResult containing the tasks and an optional cursor for the next page.

Remarks

When sessionId is provided, implementations should filter to only return tasks associated with that session. The cursor format is implementation-specific.

StoreTaskResultAsync(string, McpTaskStatus, JsonElement, string?, CancellationToken)

Stores the final result of a task that has reached a terminal status.

public Task<McpTask> StoreTaskResultAsync(string taskId, McpTaskStatus status, JsonElement result, string? sessionId = null, CancellationToken cancellationToken = default)

Parameters

taskId string

The unique identifier of the task.

status McpTaskStatus

The terminal status: Completed or Failed.

result JsonElement

The operation result to store as a JSON element.

sessionId string

Optional session identifier for access control.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task<McpTask>

A task representing the asynchronous operation.

Remarks

The status must be either Completed or Failed. This method updates the task status and stores the result for later retrieval via GetTaskResultAsync(string, string?, CancellationToken).

Implementations should throw InvalidOperationException if called on a task that is already in a terminal state, to prevent result overwrites.

UpdateTaskStatusAsync(string, McpTaskStatus, string?, string?, CancellationToken)

Updates the status and optional status message of a task.

public Task<McpTask> UpdateTaskStatusAsync(string taskId, McpTaskStatus status, string? statusMessage, string? sessionId = null, CancellationToken cancellationToken = default)

Parameters

taskId string

The unique identifier of the task.

status McpTaskStatus

The new status to set.

statusMessage string

Optional diagnostic message describing the status change.

sessionId string

Optional session identifier for access control.

cancellationToken CancellationToken

Cancellation token for the operation.

Returns

Task<McpTask>

A task representing the asynchronous operation.

Remarks

This method updates the task's Status, StatusMessage, and LastUpdatedAt properties. Common uses include transitioning to Cancelled, InputRequired, or updating progress messages while in Working status.