mirror of
https://github.com/mcp-use/mcp-use.git
synced 2026-09-14 18:06:01 +08:00
68afda5885
* docs: remove stale feedback block and orphaned anchor from docs.json * chore(docs): make Typescript more prominent * chore(docs): Update `welcome.mdx` * docs: rewrite TypeScript quickstart and welcome pages Refocus the quickstart on create-mcp-use-app (scaffold, run, and deploy a first MCP server) and drop the agent/client/server primer table and diagram. Convert the welcome page's server + widget example from Tabs to CodeGroup and tighten the intro wording. * docs: remove stale server templates page and fix its references Delete the typescript/server/templates page and repoint the home templates tip to the quickstart, which now covers create-mcp-use-app. * docs(typescript): fix dead example links to real example paths The 'see a full example' links pointed at GitHub folders that 404 or contain only a README. Corrected to the real runnable examples under libraries/typescript/packages/mcp-use/examples/, verified against origin/main (incl. matching cd commands): - installation: examples/server -> packages/.../examples/server - client-configuration: a .py link -> real TS multi-server example - code-mode: examples/client/* -> examples/agent/code-mode/* - elicitation, sampling, notifications: server/X -> server/features/X - supabase: server/supabase -> server/deployment/supabase - clerk: restore missing packages/mcp-use/ path segment Quickstart links were already fixed by the quickstart rewrite (e6903716). Part of the docs audit (MCP-2466). * docs(typescript): rewrite Agent and Client introduction pages Rewrite the Agent and Client intro pages to be task-oriented and scannable: concise feature lists with cross-links, runnable quick-start examples, and added API reference sections. Drop stale CodeSandbox embeds and outdated model names. * docs(typescript): fix MCPServer class name casing in server reference The API Reference heading, prose, and class signature used McpServer; the real SDK export is MCPServer. Corrected all three occurrences in server/index.mdx. * docs: add redirect for bare /typescript/server path Routes the bare /typescript/server path to its index page now that the server section has been restructured. Claude-Session: https://claude.ai/code/session_015uioJjKTAZXGQpbXHUHZWp * docs(typescript): fix broken code examples across MCP Server & Apps section Fix all 102 confirmed code defects found in the MCP Server & MCP Apps documentation audit (47 pages, 401 code blocks), verified against the mcp-use@1.32 SDK source. The recurring patterns that made copy-pasted examples fail to compile or run are now corrected everywhere they appeared: - server.start() -> await server.listen() (no start() method exists) - bare-object tool returns wrapped in object()/text() response helpers; catch blocks renamed so they no longer shadow the error() helper - prompt messages use role:"user" with typed { type:"text" } content instead of the invalid role:"system" + bare-string shape - auth reads ctx.auth.user.userId (not ctx.auth.userId); user fields live under ctx.auth.user, scopes/permissions stay top-level - security: remove verifyJwt: process.env.NODE_ENV === 'production' from all six OAuth provider pages (off-prod it skips signature verification and accepts forged tokens); rely on the secure default, with a warning never to disable it - correct import subpaths: Logger/MCPClient from mcp-use, response helpers and server symbols from mcp-use/server, MCPClient as BrowserMCPClient from mcp-use/browser; drop the unexported getMcpAppsBridge - useWidget generics use the real <TProps, TState, TOutput, ...> order; remove the non-existent notifyIntrinsicHeight (auto-size via McpUseProvider) - fix the deployment URL to <id>.run.mcp-use.com/mcp, add missing z/helper imports, add the --branch/--dockerfile CLI options, and clean up em dashes and bare/malformed code fences Each page was fixed and then independently re-verified against the SDK source, with a repo-wide pattern sweep confirming no instances remain. Structural IA changes (moving widget-components to /react/, orphan redirects) are intentionally deferred to the docs rewrite. * docs(typescript): restructure MCP Server & MCP Apps IA Promote MCP Apps to its own top-level section in the TypeScript SDK Docs tab and move the 9 React widget-component pages out of /server/widget-components/ into /typescript/react/. - Move 9 React component pages to typescript/react/ (git renames) with 9 redirects - Promote MCP Apps to a top-level group (Overview pages + React subgroup) - Remove the duplicate MCP Apps group from the Home product nav; rehome guides/chatgpt-apps-flow under MCP Apps so it no longer orphans - Move cli-reference out of MCP Server into a new Tooling group - Relocate response-helpers -> Core Components, openapi -> Advanced Features, nextjs-drop-in -> Deployment - Repoint all widget-components links to /typescript/react/ - Fix 3 broken anchor links (inspector CLI env var, mcp-apps metadata, auth providers) Structure-only change; no page content rewrites. Refs MCP-2466. * docs: refresh TypeScript server app docs * docs: add TypeScript API reference * docs: streamline TypeScript server navigation * docs: rewrite core TypeScript server guides * docs: rewrite advanced TypeScript server guides * docs: rewrite TypeScript server OAuth guides * docs: rewrite TypeScript server session storage guides * docs: rewrite MCP Apps section * docs: add TypeScript MCP client API reference * docs: add TypeScript MCP agent API reference * docs: reorder TypeScript API reference nav * docs: reorganize TypeScript tooling nav * docs: rewrite inspector guides * docs: rewrite MCP server tunneling guide * docs: rewrite CLI client and reference docs * docs: finalize TypeScript documentation rewrite * docs: move inspector updates under get started * Fix Mintlify validation errors * Fix Mintlify broken links * docs: update Manufact Cloud deployment guide * chore: retrigger Mintlify docs preview * Fix MDX comment syntax on home page * docs: rework TypeScript server examples * docs: fix server docs links * docs: restore SDK links in home sidebar * docs: move SDK links to end of home sidebar
113 lines
5.1 KiB
Plaintext
113 lines
5.1 KiB
Plaintext
---
|
|
title: "Notifications"
|
|
description: "MCP servers can send various notifications to the client to signal events or provide updates on long-running tasks. This is distinct from logging, which is handled separately."
|
|
icon: "bell-ring"
|
|
---
|
|
|
|
|
|
`mcp-use` allows you to handle these notifications by providing a `message_handler` to the `MCPClient`.
|
|
|
|
## Server-Side: Sending Notifications
|
|
|
|
On the server (using `fastmcp`), you can send notifications from within a tool's context (`ctx`). Here's an example of a tool that sends multiple types of notifications, including progress updates.
|
|
|
|
```python filename="server.py"
|
|
from fastmcp import Context, FastMCP
|
|
|
|
mcp = FastMCP(name="PrimitiveServer")
|
|
|
|
@mcp.tool()
|
|
async def long_running_task(task_name: str, ctx: Context, steps: int = 5) -> str:
|
|
"""Execute a task with progress updates."""
|
|
# This is a log message, not a notification
|
|
await ctx.info(f"Starting: {task_name}")
|
|
|
|
for i in range(steps):
|
|
progress = (i + 1) / steps
|
|
# These are notifications
|
|
await ctx.send_prompt_list_changed()
|
|
await ctx.send_resource_list_changed()
|
|
await ctx.send_tool_list_changed()
|
|
await ctx.report_progress(
|
|
progress=progress,
|
|
total=1.0,
|
|
message=f"Step {i + 1}/{steps}",
|
|
)
|
|
# This is another log message
|
|
await ctx.debug(f"Completed step {i + 1}")
|
|
|
|
return f"Task '{task_name}' completed"
|
|
```
|
|
|
|
## Available Notification Types
|
|
|
|
The `fastmcp` server context provides several methods for sending specific notifications. Here are the ones you can use and the corresponding type to check for in your client's `message_handler`:
|
|
|
|
- `ctx.report_progress(...)` sends a `types.ProgressNotification`. This is used to report the progress of a long-running operation.
|
|
- `ctx.send_tool_list_changed()` sends a `types.ToolListChangedNotification`. This signals that the tool list has changed (see [Tools documentation](/python/client/tools)).
|
|
- `ctx.send_resource_list_changed()` sends a `types.ResourceListChangedNotification`. This signals that the resource list has changed (see [Resources documentation](/python/client/resources)).
|
|
- `ctx.send_prompt_list_changed()` sends a `types.PromptListChangedNotification`. This signals that the prompt list has changed (see [Prompts documentation](/python/client/prompts)).
|
|
|
|
## Client-Side: Handling Notifications
|
|
|
|
On the client, you create a `message_handler` function and pass it to the `MCPClient`. This function will receive all messages from the server, including notifications.
|
|
|
|
Since the `message_handler` receives all message types (requests, notifications, exceptions), you need to check the type of the incoming message to handle it correctly. Notifications are of type `mcp.types.ServerNotification`, and their specific type is stored in the `.root` attribute.
|
|
|
|
<CodeGroup>
|
|
```python Python
|
|
import asyncio
|
|
import mcp.types as types
|
|
from mcp_use import MCPClient
|
|
|
|
# The message handler receives all server-sent messages
|
|
async def handle_messages(message):
|
|
# Check if the message is a server notification
|
|
if isinstance(message, types.ServerNotification):
|
|
notification = message.root
|
|
# Check the specific type of notification
|
|
if isinstance(notification, types.ProgressNotification):
|
|
params = notification.params
|
|
print(
|
|
f"Progress: {params.progress:.0%}"
|
|
f" ({params.message})"
|
|
)
|
|
elif isinstance(notification, types.PromptListChangedNotification):
|
|
print("Server prompts have changed")
|
|
elif isinstance(notification, types.ResourceListChangedNotification):
|
|
print("Server resources have changed")
|
|
elif isinstance(notification, types.ToolListChangedNotification):
|
|
print("Server tools have changed")
|
|
# Logging notifications are also sent here, but can be handled
|
|
# by a dedicated logging_callback.
|
|
elif isinstance(notification, types.LoggingMessageNotification):
|
|
pass
|
|
else:
|
|
print(f"Received unhandled notification: {notification}")
|
|
else:
|
|
# Handle other message types like requests or exceptions
|
|
print(f"Received other message type: {type(message)}")
|
|
|
|
async def test_notifications(primitive_server):
|
|
"""Tests receiving notifications from the primitive server."""
|
|
config = {"mcpServers": {"PrimitiveServer": {"url": f"{primitive_server}/mcp"}}}
|
|
client = MCPClient(config, message_handler=handle_messages)
|
|
try:
|
|
await client.create_all_sessions()
|
|
session = client.get_session("PrimitiveServer")
|
|
|
|
# This will trigger the notifications in the handler
|
|
result = await session.call_tool(
|
|
name="long_running_task",
|
|
arguments={"task_name": "test", "steps": 5}
|
|
)
|
|
assert result.content[0].text == "Task 'test' completed"
|
|
finally:
|
|
await client.close_all_sessions()
|
|
```
|
|
</CodeGroup>
|
|
|
|
<Note>
|
|
The `message_handler` is a powerful catch-all for any message from the server. By inspecting the message type, you can build rich, responsive applications that react to server-side events in real time.
|
|
</Note>
|