microsoft/semantic-kernel · error · ValueError

Request context is required for sampling function.

Error message

Request context is required for sampling function.

What it means

Raised by the MCP server sampling_function when the injected Server session is None. The function relies on Semantic Kernel's MCPPlugin to inject the live server session via the 'server' parameter (marked include_in_function_choices=False). If the function is invoked outside that injection path, server is None and sampling cannot reach request_context.session.create_message.

Source

Thrown at python/samples/demos/mcp_server/mcp_server_with_sampling.py:71

Include the output in raw markdown.
"""


@kernel_function(
    name="run_prompt",
    description="This run the prompts for a full set of release notes based on the PR messages given.",
)
async def sampling_function(
    messages: Annotated[str, "The list of PR messages, as a string with newlines"],
    temperature: float = 0.0,
    max_tokens: int = 1000,
    # The include_in_function_choices is set to False, so it won't be included in the function choices,
    # but it will get the server instance from the MCPPlugin that consumes this server.
    server: Annotated[Server | None, "The server session", {"include_in_function_choices": False}] = None,
) -> str:
    if not server:
        raise ValueError("Request context is required for sampling function.")
    sampling_response = await server.request_context.session.create_message(
        messages=[
            types.SamplingMessage(role="user", content=types.TextContent(type="text", text=messages)),
        ],
        max_tokens=max_tokens,
        temperature=temperature,
        model_preferences=types.ModelPreferences(
            hints=[types.ModelHint(name="gpt-4o-mini")],
        ),
    )
    logger.info(f"Sampling response: {sampling_response}")
    return sampling_response.content.text


def run() -> None:
    """Run the MCP server with the release notes prompt template."""
    kernel = Kernel()
    kernel.add_function("release_notes", sampling_function)

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Invoke sampling_function only through the kernel/MCP plugin so the Server is injected.
  2. Ensure the MCP server hosting this tool is registered with MCPPlugin before the function is called.
  3. Verify the 'server' parameter annotation and metadata match what MCPPlugin expects for injection.
  4. Do not unit-test by calling the function with server=None; pass a mock Server with a request_context.session.

Example fix

// before
await sampling_function(messages='pr list')  # server defaults to None

// after
# invoke through the kernel so MCPPlugin injects the server
result = await kernel.invoke(plugin_name='MCPPlugin', function_name='run_prompt', messages='pr list')
Defensive patterns

Strategy: validation

Validate before calling

if server is None:
    raise ValueError('sampling_function must be invoked through the kernel/MCPPlugin so the server is injected')
sampling_response = await server.request_context.session.create_message(...)

Type guard

def has_server_session(server) -> bool:
    return (
        server is not None
        and getattr(getattr(server, 'request_context', None), 'session', None) is not None
    )

Prevention

When it happens

Trigger: Calling sampling_function() directly/standalone without going through the kernel function pipeline that injects the server; the MCPPlugin failed to bind the server to the parameter; the server is not actually running/registered.

Common situations: See trigger scenarios.

Related errors


AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13). Data as JSON: /api/errors/d7082cc4ccf65c49. Report an issue: GitHub.