Follow Discord
Sweep 22 Oct 2026 · 04:32Z Build v2.1.308 527 read Stable v2.1.308 Latest v2.1.308 Next v2.1.308 Feeds RSS JSON llms.txt llms-full.txt Unofficial
One capture · mcp

One read of Model Context Protocolmcp-20261020T200724Z

306 pages moved out of 357 read.

Pages moved 306 significant first
Pages read 357 in this capture
Captured 20:07 UTC
Corpus hash 077a51951f96 corpus-hash

What this read moved

51-75 of 306, page 3 of 13

This capture is too large to show at once. Changes 51-75 of 306 are below, significant first; the rest are on the following screens.

docs/2025-06-18/learn/versioning Changed · +5 / -5 lines

from line 3
33The Model Context Protocol uses string-based version identifiers following the format
44`YYYY-MM-DD`, to indicate the last date backwards incompatible changes were made.
55 
6<Info>
7 The protocol version will *not* be incremented when the
8 protocol is updated, as long as the changes maintain backwards compatibility. This allows
9 for incremental improvements while preserving interoperability.
10</Info>
6> [!NOTE]
7>
8> The protocol version will *not* be incremented when the
9> protocol is updated, as long as the changes maintain backwards compatibility. This allows
10> for incremental improvements while preserving interoperability.
1111 
1212## Revisions
1313 

docs/2025-06-18/sdk Changed · +16 / -18 lines

from line 8
88 
99| SDK | Repository | Tier |
1010| :- | :- | -: |
11| <Icon icon="square-js" size={24} />   [TypeScript](https://ts.sdk.modelcontextprotocol.io) | [modelcontextprotocol/typescript-sdk](https://github.com/modelcontextprotocol/typescript-sdk) | <Badge color="blue" shape="pill">Tier 1</Badge> |
12| <Icon icon="python" size={24} />   [Python](https://py.sdk.modelcontextprotocol.io) | [modelcontextprotocol/python-sdk](https://github.com/modelcontextprotocol/python-sdk) | <Badge color="blue" shape="pill">Tier 1</Badge> |
13| <Icon icon="square-c" size={24} />   [C#](https://csharp.sdk.modelcontextprotocol.io) | [modelcontextprotocol/csharp-sdk](https://github.com/modelcontextprotocol/csharp-sdk) | <Badge color="blue" shape="pill">Tier 1</Badge> |
14| <Icon icon="golang" size={24} />   [Go](https://go.sdk.modelcontextprotocol.io) | [modelcontextprotocol/go-sdk](https://github.com/modelcontextprotocol/go-sdk) | <Badge color="blue" shape="pill">Tier 1</Badge> |
15| <Icon icon="java" size={24} />   [Java](https://java.sdk.modelcontextprotocol.io) | [modelcontextprotocol/java-sdk](https://github.com/modelcontextprotocol/java-sdk) | <Badge color="purple" shape="pill">Tier 2</Badge> |
16| <Icon icon="rust" size={24} />   [Rust](https://rust.sdk.modelcontextprotocol.io) | [modelcontextprotocol/rust-sdk](https://github.com/modelcontextprotocol/rust-sdk) | <Badge color="purple" shape="pill">Tier 2</Badge> |
17| <Icon icon="swift" size={24} />   Swift | [modelcontextprotocol/swift-sdk](https://github.com/modelcontextprotocol/swift-sdk) | <Badge color="orange" shape="pill">Tier 3</Badge> |
18| <Icon icon="gem" size={24} />   [Ruby](https://ruby.sdk.modelcontextprotocol.io) | [modelcontextprotocol/ruby-sdk](https://github.com/modelcontextprotocol/ruby-sdk) | <Badge color="orange" shape="pill">Tier 3</Badge> |
19| <Icon icon="php" size={24} />   [PHP](https://php.sdk.modelcontextprotocol.io) | [modelcontextprotocol/php-sdk](https://github.com/modelcontextprotocol/php-sdk) | <Badge color="orange" shape="pill">Tier 3</Badge> |
20| <Icon icon="square-k" size={24} />   [Kotlin](https://kotlin.sdk.modelcontextprotocol.io) | [modelcontextprotocol/kotlin-sdk](https://github.com/modelcontextprotocol/kotlin-sdk) | <Badge color="orange" shape="pill">Tier 3</Badge> |
11|   [TypeScript](https://ts.sdk.modelcontextprotocol.io) | [modelcontextprotocol/typescript-sdk](https://github.com/modelcontextprotocol/typescript-sdk) | Tier 1 |
12|   [Python](https://py.sdk.modelcontextprotocol.io) | [modelcontextprotocol/python-sdk](https://github.com/modelcontextprotocol/python-sdk) | Tier 1 |
13|   [C#](https://csharp.sdk.modelcontextprotocol.io) | [modelcontextprotocol/csharp-sdk](https://github.com/modelcontextprotocol/csharp-sdk) | Tier 1 |
14|   [Go](https://go.sdk.modelcontextprotocol.io) | [modelcontextprotocol/go-sdk](https://github.com/modelcontextprotocol/go-sdk) | Tier 1 |
15|   [Java](https://java.sdk.modelcontextprotocol.io) | [modelcontextprotocol/java-sdk](https://github.com/modelcontextprotocol/java-sdk) | Tier 2 |
16|   [Rust](https://rust.sdk.modelcontextprotocol.io) | [modelcontextprotocol/rust-sdk](https://github.com/modelcontextprotocol/rust-sdk) | Tier 2 |
17|   Swift | [modelcontextprotocol/swift-sdk](https://github.com/modelcontextprotocol/swift-sdk) | Tier 3 |
18|   [Ruby](https://ruby.sdk.modelcontextprotocol.io) | [modelcontextprotocol/ruby-sdk](https://github.com/modelcontextprotocol/ruby-sdk) | Tier 3 |
19|   [PHP](https://php.sdk.modelcontextprotocol.io) | [modelcontextprotocol/php-sdk](https://github.com/modelcontextprotocol/php-sdk) | Tier 3 |
20|   [Kotlin](https://kotlin.sdk.modelcontextprotocol.io) | [modelcontextprotocol/kotlin-sdk](https://github.com/modelcontextprotocol/kotlin-sdk) | Tier 3 |
2121 
2222See [SDK Tiering System](/community/sdk-tiers) for details on what each tier means.
2323 
from line 36
3636 
3737Ready to start building with MCP? Choose your path:
3838 
39<CardGroup cols={2}>
40 <Card title="Build a Server" icon="server" href="/docs/2025-06-18/develop/build-server">
41 Learn how to create your first MCP server
42 </Card>
39> **[Build a Server](/docs/2025-06-18/develop/build-server)**
40>
41> Learn how to create your first MCP server
4342 
44 <Card title="Build a Client" icon="computer" href="/docs/2025-06-18/develop/build-client">
45 Create applications that connect to MCP servers
46 </Card>
47</CardGroup>
43> **[Build a Client](/docs/2025-06-18/develop/build-client)**
44>
45> Create applications that connect to MCP servers
4846 

docs/2025-06-18/tools/debugging Changed · +46 / -54 lines

from line 32
3232logged to stderr (standard error) will be captured by the host application
3333automatically.
3434 
35<Warning>
36 Local MCP servers should not log messages to stdout (standard out), as this
37 will interfere with protocol operation.
38</Warning>
35> [!WARNING]
36>
37> Local MCP servers should not log messages to stdout (standard out), as this
38> will interfere with protocol operation.
3939 
4040For servers using the
4141[Streamable HTTP transport](/specification/2025-06-18/basic/transports#streamable-http),
from line 48
4848For all [transports](/specification/2025-06-18/basic/transports), you can also
4949provide logging to the client by sending a log message notification:
5050 
51<CodeGroup>
52 ```python Python theme={null}
53 @server.tool()
54 async def my_tool(ctx: Context) -> str:
55 await ctx.session.send_log_message(
56 level="info",
57 data="Server started successfully",
58 )
59 return "done"
60 ```
51```python Python theme={null}
52@server.tool()
53async def my_tool(ctx: Context) -> str:
54 await ctx.session.send_log_message(
55 level="info",
56 data="Server started successfully",
57 )
58 return "done"
59```
6160 
62 ```typescript TypeScript theme={null}
63 await server.sendLoggingMessage({
64 level: "info",
65 data: "Server started successfully",
66 });
67 ```
68</CodeGroup>
61```typescript TypeScript theme={null}
62await server.sendLoggingMessage({
63 level: "info",
64 data: "Server started successfully",
65});
66```
6967 
7068MCP defines eight
7169[RFC 5424 severity levels](/specification/2025-06-18/server/utilities/logging#log-levels)
from line 189
191189hover over the **Connectors** menu to see connected servers and available
192190tools.
193191 
194<img src="https://mintcdn.com/mcp/zNouQwo2h8cbxlDS/images/available-mcp-tools.png?fit=max&auto=format&n=zNouQwo2h8cbxlDS&q=85&s=e2ace1ac88895a5fe30ebd8d01456bc3" alt="Available MCP tools" width="437" height="244" data-path="images/available-mcp-tools.png" />
192![Available MCP tools](https://mintcdn.com/mcp/zNouQwo2h8cbxlDS/images/available-mcp-tools.png?fit=max\&auto=format\&n=zNouQwo2h8cbxlDS\&q=85\&s=e2ace1ac88895a5fe30ebd8d01456bc3)
195193 
196194### Viewing logs
197195 
from line 198
200198* macOS: `~/Library/Logs/Claude`
201199* Windows: `%APPDATA%\Claude\logs`
202200 
203<CodeGroup>
204 ```bash macOS theme={null}
205 tail -n 20 -F ~/Library/Logs/Claude/mcp*.log
206 ```
201```bash macOS theme={null}
202tail -n 20 -F ~/Library/Logs/Claude/mcp*.log
203```
207204 
208 ```powershell Windows theme={null}
209 type "$env:AppData\Claude\logs\mcp*.log"
210 ```
211</CodeGroup>
205```powershell Windows theme={null}
206type "$env:AppData\Claude\logs\mcp*.log"
207```
212208 
213209The logs capture:
214210 
from line 220
224220 
2252211. Create a `developer_settings.json` file with `allowDevTools` set to true:
226222 
227<CodeGroup>
228 ```bash macOS theme={null}
229 echo '{"allowDevTools": true}' > ~/Library/Application\ Support/Claude/developer_settings.json
230 ```
223```bash macOS theme={null}
224echo '{"allowDevTools": true}' > ~/Library/Application\ Support/Claude/developer_settings.json
225```
231226 
232 ```powershell Windows theme={null}
233 '{"allowDevTools": true}' | Set-Content "$env:AppData\Claude\developer_settings.json"
234 ```
235</CodeGroup>
227```powershell Windows theme={null}
228'{"allowDevTools": true}' | Set-Content "$env:AppData\Claude\developer_settings.json"
229```
236230 
2372312. Open DevTools: `Command-Option-I` (macOS) or `Ctrl+Alt+I` (Windows)
238232 
from line 327
333327 
334328## Next steps
335329 
336<CardGroup cols={2}>
337 <Card title="MCP Inspector" icon="magnifying-glass" href="/docs/2025-06-18/tools/inspector">
338 Learn to use the MCP Inspector
339 </Card>
330> **[MCP Inspector](/docs/2025-06-18/tools/inspector)**
331>
332> Learn to use the MCP Inspector
340333 
341 <Card title="Build an MCP server" icon="code" href="/docs/2025-06-18/develop/build-server">
342 Walk through building a server from scratch
343 </Card>
334> **[Build an MCP server](/docs/2025-06-18/develop/build-server)**
335>
336> Walk through building a server from scratch
344337 
345 <Card title="Connect local servers" icon="plug" href="/docs/2025-06-18/develop/connect-local-servers">
346 Full claude\_desktop\_config.json reference and troubleshooting
347 </Card>
348</CardGroup>
338> **[Connect local servers](/docs/2025-06-18/develop/connect-local-servers)**
339>
340> Full claude\_desktop\_config.json reference and troubleshooting
349341 

docs/2025-06-18/tools/inspector Changed · +36 / -44 lines

from line 22
2222 
2323A common way to start server packages from [npm](https://npmjs.com) or [PyPI](https://pypi.org).
2424 
25<Tabs>
26 <Tab title="npm package">
27 ```bash theme={null}
28 npx -y @modelcontextprotocol/inspector npx <package-name> <args>
29 # For example
30 npx -y @modelcontextprotocol/inspector npx @modelcontextprotocol/server-filesystem /Users/username/Desktop
31 ```
32 </Tab>
25**npm package**
3326 
34 <Tab title="PyPI package">
35 ```bash theme={null}
36 npx @modelcontextprotocol/inspector uvx <package-name> <args>
37 # For example
38 npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git
39 ```
40 </Tab>
41</Tabs>
27```bash theme={null}
28npx -y @modelcontextprotocol/inspector npx <package-name> <args>
29# For example
30npx -y @modelcontextprotocol/inspector npx @modelcontextprotocol/server-filesystem /Users/username/Desktop
31```
4232 
33**PyPI package**
34 
35```bash theme={null}
36npx @modelcontextprotocol/inspector uvx <package-name> <args>
37# For example
38npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git
39```
40 
4341#### Inspecting locally developed servers
4442 
4543To inspect servers locally developed or downloaded as a repository, the most common
4644way is:
4745 
48<Tabs>
49 <Tab title="TypeScript">
50 ```bash theme={null}
51 npx @modelcontextprotocol/inspector node path/to/server/index.js args...
52 ```
53 </Tab>
46**TypeScript**
5447 
55 <Tab title="Python">
56 ```bash theme={null}
57 npx @modelcontextprotocol/inspector \
58 uv \
59 --directory path/to/server \
60 run \
61 package-name \
62 args...
63 ```
64 </Tab>
65</Tabs>
48```bash theme={null}
49npx @modelcontextprotocol/inspector node path/to/server/index.js args...
50```
6651 
52**Python**
53 
54```bash theme={null}
55npx @modelcontextprotocol/inspector \
56 uv \
57 --directory path/to/server \
58 run \
59 package-name \
60 args...
61```
62 
6763Please carefully read any attached README for the most accurate instructions.
6864 
6965## Feature overview
7066 
71<Frame caption="The MCP Inspector interface">
72 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/mcp-inspector.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=83b12e2a457c96ef4ad17c7357236290" width="2888" height="1761" data-path="images/mcp-inspector.png" />
73</Frame>
67![](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/mcp-inspector.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=83b12e2a457c96ef4ad17c7357236290)
7468 
7569The Inspector provides several features for interacting with your MCP server:
7670 
from line 123
129123 
130124## Next steps
131125 
132<CardGroup cols={2}>
133 <Card title="Inspector Repository" icon="github" href="https://github.com/modelcontextprotocol/inspector">
134 Check out the MCP Inspector source code
135 </Card>
126> **[Inspector Repository](https://github.com/modelcontextprotocol/inspector)**
127>
128> Check out the MCP Inspector source code
136129 
137 <Card title="Debugging Guide" icon="bug" href="/docs/2025-06-18/tools/debugging">
138 Learn about broader debugging strategies
139 </Card>
140</CardGroup>
130> **[Debugging Guide](/docs/2025-06-18/tools/debugging)**
131>
132> Learn about broader debugging strategies
141133 

docs/2025-06-18/tutorials/security/authorization Changed · +841 / -861 lines

The two sides of this change are more than 400 edits apart, too far apart to line up, so this is the differ's own diff of it and the words inside a line are not marked.

from line 16
1616* You're building for enterprise environments with strict access controls
1717* You want to implement rate limiting or usage tracking per user
1818 
19<Tip>
20 **Authorization for Local MCP Servers**
21 
22 For MCP servers using the [STDIO transport](/specification/2025-06-18/basic/transports#stdio), you can use environment-based credentials or credentials provided by third-party libraries embedded directly in the MCP server instead. Because a STDIO-built MCP server runs locally, it has access to a range of flexible options when it comes to acquiring user credentials that may or may not rely on in-browser authentication and authorization flows.
23 
24 OAuth flows, in turn, are designed for HTTP-based transports where the MCP server is remotely-hosted and the client uses OAuth to establish that a user is authorized to access said remote server.
25</Tip>
19> [!TIP]
20>
21> **Authorization for Local MCP Servers**
22>
23> For MCP servers using the [STDIO transport](/specification/2025-06-18/basic/transports#stdio), you can use environment-based credentials or credentials provided by third-party libraries embedded directly in the MCP server instead. Because a STDIO-built MCP server runs locally, it has access to a range of flexible options when it comes to acquiring user credentials that may or may not rely on in-browser authentication and authorization flows.
24>
25> OAuth flows, in turn, are designed for HTTP-based transports where the MCP server is remotely-hosted and the client uses OAuth to establish that a user is authorized to access said remote server.
2626 
2727## The Authorization Flow: Step by Step
2828 
2929Let's walk through what happens when a client wants to connect to your protected MCP server:
3030 
31<Steps>
32 <Step title="Initial Handshake">
33 When your MCP client first tries to connect, your server responds with a `401 Unauthorized` and tells the client where to find authorization information, captured in a [Protected Resource Metadata (PRM) document](https://datatracker.ietf.org/doc/html/rfc9728). The document is hosted by the MCP server, follows a predictable path pattern, and is provided to the client in the `resource_metadata` parameter within the `WWW-Authenticate` header.
34 
35 ```http theme={null}
36 HTTP/1.1 401 Unauthorized
37 WWW-Authenticate: Bearer realm="mcp",
38 resource_metadata="https://your-server.com/.well-known/oauth-protected-resource"
39 ```
40 
41 This tells the client that authorization is required for the MCP server and where to get the necessary information to kickstart the authorization flow.
42 </Step>
43 
44 <Step title="Protected Resource Metadata Discovery">
45 With the URI pointer to the PRM document, the client will fetch the metadata to learn about the authorization server, supported scopes, and other resource information. The data is typically encapsulated in a JSON blob, similar to the one below.
46 
47 ```json theme={null}
48 {
49 "resource": "https://your-server.com/mcp",
50 "authorization_servers": ["https://auth.your-server.com"],
51 "scopes_supported": ["mcp:tools", "mcp:resources"]
52 }
53 ```
54 
55 You can see a more comprehensive example in [RFC 9728 Section 3.2](https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata-r).
56 </Step>
57 
58 <Step title="Authorization Server Discovery">
59 Next, the client discovers what the authorization server can do by fetching its metadata. If the PRM document lists more than one authorization server, the client can decide which one to use.
60 
61 With an authorization server selected, the client will then construct a standard metadata URI and issue a request to the [OpenID Connect (OIDC) Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) or [OAuth 2.0 Auth Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) endpoints (depending on authorization server support)
62 and retrieve another set of metadata properties that will allow it to know the endpoints it needs to complete the authorization flow.
63 
64 ```json theme={null}
65 {
66 "issuer": "https://auth.your-server.com",
67 "authorization_endpoint": "https://auth.your-server.com/authorize",
68 "token_endpoint": "https://auth.your-server.com/token",
69 "registration_endpoint": "https://auth.your-server.com/register"
70 }
71 ```
72 </Step>
73 
74 <Step title="Client Registration">
75 With all the metadata out of the way, the client now needs to make sure that it's registered with the authorization server. This can be done in two ways.
76 
77 First, the client can be **pre-registered** with a given authorization server, in which case it can have embedded client registration information that it uses to complete the authorization flow.
78 
79 Alternatively, the client can use **Dynamic Client Registration** (DCR) to dynamically register itself with the authorization server. The latter scenario requires the authorization server to support DCR. If the authorization server does support DCR, the client will send a request to the `registration_endpoint` with its information:
80 
81 ```json theme={null}
82 {
83 "client_name": "My MCP Client",
84 "redirect_uris": ["http://localhost:3000/callback"],
85 "grant_types": ["authorization_code", "refresh_token"],
86 "response_types": ["code"]
87 }
88 ```
89 
90 If the registration succeeds, the authorization server will return a JSON blob with client registration information.
91 
92 <Tip>
93 **No DCR or Pre-Registration**
94 
95 In case an MCP client connects to an MCP server that doesn't use an authorization server that supports DCR and the client is not pre-registered with said authorization server, it's the responsibility of the client developer to provide an affordance for the end-user to enter client information manually.
96 </Tip>
97 </Step>
98 
99 <Step title="User Authorization">
100 The client will now need to open a browser to the `/authorize` endpoint, where the user can log in and grant the required permissions. The authorization server will then redirect back to the client with an authorization code that the client exchanges for tokens:
101 
102 ```json theme={null}
103 {
104 "access_token": "eyJhbGciOiJSUzI1NiIs...",
105 "refresh_token": "def502...",
106 "token_type": "Bearer",
107 "expires_in": 3600
108 }
109 ```
110 
111 The access token is what the client will use to authenticate requests to the MCP server. This step follows standard [OAuth 2.1 authorization code with PKCE](https://oauth.net/2/grant-types/authorization-code/) conventions.
112 </Step>
113 
114 <Step title="Making Authenticated Requests">
115 Finally, the client can make requests to your MCP server using the access token embedded in the `Authorization` header:
116 
117 ```http theme={null}
118 GET /mcp HTTP/1.1
119 Host: your-server.com
120 Authorization: Bearer eyJhbGciOiJSUzI1NiIs...
121 ```
122 
123 The MCP server will need to validate the token and process the request if the token is valid and has the required permissions.
124 </Step>
125</Steps>
31**1. Initial Handshake**
32 
33When your MCP client first tries to connect, your server responds with a `401 Unauthorized` and tells the client where to find authorization information, captured in a [Protected Resource Metadata (PRM) document](https://datatracker.ietf.org/doc/html/rfc9728). The document is hosted by the MCP server, follows a predictable path pattern, and is provided to the client in the `resource_metadata` parameter within the `WWW-Authenticate` header.
34 
35```http theme={null}
36HTTP/1.1 401 Unauthorized
37WWW-Authenticate: Bearer realm="mcp",
38 resource_metadata="https://your-server.com/.well-known/oauth-protected-resource"
39```
40 
41This tells the client that authorization is required for the MCP server and where to get the necessary information to kickstart the authorization flow.
42 
43**2. Protected Resource Metadata Discovery**
44 
45With the URI pointer to the PRM document, the client will fetch the metadata to learn about the authorization server, supported scopes, and other resource information. The data is typically encapsulated in a JSON blob, similar to the one below.
46 
47```json theme={null}
48{
49 "resource": "https://your-server.com/mcp",
50 "authorization_servers": ["https://auth.your-server.com"],
51 "scopes_supported": ["mcp:tools", "mcp:resources"]
52}
53```
54 
55You can see a more comprehensive example in [RFC 9728 Section 3.2](https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata-r).
56 
57**3. Authorization Server Discovery**
58 
59Next, the client discovers what the authorization server can do by fetching its metadata. If the PRM document lists more than one authorization server, the client can decide which one to use.
60 
61With an authorization server selected, the client will then construct a standard metadata URI and issue a request to the [OpenID Connect (OIDC) Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) or [OAuth 2.0 Auth Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) endpoints (depending on authorization server support)
62and retrieve another set of metadata properties that will allow it to know the endpoints it needs to complete the authorization flow.
63 
64```json theme={null}
65{
66 "issuer": "https://auth.your-server.com",
67 "authorization_endpoint": "https://auth.your-server.com/authorize",
68 "token_endpoint": "https://auth.your-server.com/token",
69 "registration_endpoint": "https://auth.your-server.com/register"
70}
71```
72 
73**4. Client Registration**
74 
75With all the metadata out of the way, the client now needs to make sure that it's registered with the authorization server. This can be done in two ways.
76 
77First, the client can be **pre-registered** with a given authorization server, in which case it can have embedded client registration information that it uses to complete the authorization flow.
78 
79Alternatively, the client can use **Dynamic Client Registration** (DCR) to dynamically register itself with the authorization server. The latter scenario requires the authorization server to support DCR. If the authorization server does support DCR, the client will send a request to the `registration_endpoint` with its information:
80 
81```json theme={null}
82{
83 "client_name": "My MCP Client",
84 "redirect_uris": ["http://localhost:3000/callback"],
85 "grant_types": ["authorization_code", "refresh_token"],
86 "response_types": ["code"]
87}
88```
89 
90If the registration succeeds, the authorization server will return a JSON blob with client registration information.
91 
92> [!TIP]
93>
94> **No DCR or Pre-Registration**
95>
96> In case an MCP client connects to an MCP server that doesn't use an authorization server that supports DCR and the client is not pre-registered with said authorization server, it's the responsibility of the client developer to provide an affordance for the end-user to enter client information manually.
97 
98**5. User Authorization**
99 
100The client will now need to open a browser to the `/authorize` endpoint, where the user can log in and grant the required permissions. The authorization server will then redirect back to the client with an authorization code that the client exchanges for tokens:
101 
102```json theme={null}
103{
104 "access_token": "eyJhbGciOiJSUzI1NiIs...",
105 "refresh_token": "def502...",
106 "token_type": "Bearer",
107 "expires_in": 3600
108}
109```
110 
111The access token is what the client will use to authenticate requests to the MCP server. This step follows standard [OAuth 2.1 authorization code with PKCE](https://oauth.net/2/grant-types/authorization-code/) conventions.
112 
113**6. Making Authenticated Requests**
114 
115Finally, the client can make requests to your MCP server using the access token embedded in the `Authorization` header:
116 
117```http theme={null}
118GET /mcp HTTP/1.1
119Host: your-server.com
120Authorization: Bearer eyJhbGciOiJSUzI1NiIs...
121```
122 
123The MCP server will need to validate the token and process the request if the token is valid and has the required permissions.
126124 
127125## Implementation Example
128126 
from line 138
140138 
141139This command will pull the Keycloak container image locally and bootstrap the basic configuration. It will run on port `8080` and have an `admin` user with `admin` password.
142140 
143<Warning>
144 **Not for Production**
145 
146 The configuration above may be suitable for testing and experimentation; however, you should never use it in production. Refer to the [Configuring Keycloak for production](https://www.keycloak.org/server/configuration-production) guide for additional details on how to deploy the authorization server for scenarios that require reliability, security, and high availability.
147</Warning>
141> [!WARNING]
142>
143> **Not for Production**
144>
145> The configuration above may be suitable for testing and experimentation; however, you should never use it in production. Refer to the [Configuring Keycloak for production](https://www.keycloak.org/server/configuration-production) guide for additional details on how to deploy the authorization server for scenarios that require reliability, security, and high availability.
148146 
149147You will be able to access the Keycloak authorization server from your browser at `http://localhost:8080`.
150148 
151<Frame>
152 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-browser.png?fit=max&auto=format&n=sAd4SGUO-cEUqgzn&q=85&s=cba689d986e113cbe937d732ac0558b6" alt="Keycloak admin dashboard authentication dialog." width="1834" height="1450" data-path="images/tutorial-authorization/keycloak-browser.png" />
153</Frame>
149![Keycloak admin dashboard authentication dialog.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-browser.png?fit=max\&auto=format\&n=sAd4SGUO-cEUqgzn\&q=85\&s=cba689d986e113cbe937d732ac0558b6)
154150 
155151When running with the default configuration, Keycloak will already support many of the capabilities that we need for MCP servers, including Dynamic Client Registration. You can check this by looking at the OIDC configuration, available at:
156152 
from line 158
162158 
163159Go to **Client scopes** in the Keycloak dashboard and create a new `mcp:tools` scope. We will use this to access all of the tools on our MCP server.
164160 
165<Frame>
166 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-scopes.png?fit=max&auto=format&n=sAd4SGUO-cEUqgzn&q=85&s=3cd49dc2e070027609ae495751e0db58" alt="Configuring Keycloak scopes." width="1999" height="1710" data-path="images/tutorial-authorization/keycloak-scopes.png" />
167</Frame>
161![Configuring Keycloak scopes.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-scopes.png?fit=max\&auto=format\&n=sAd4SGUO-cEUqgzn\&q=85\&s=3cd49dc2e070027609ae495751e0db58)
168162 
169163After creating the scope, make sure that you assign its type to **Default** and have flipped the **Include in token scope** switch, as this will be needed for token validation.
170164 
from line 166
172166 
173167To do this, open your `mcp:tools` client scope and click on **Mappers**, followed by **Configure a new mapper**. Select **Audience**.
174168 
175<Frame>
176 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/scope-add-audience.gif?s=6ea9cf20c397f4c79c491c2e39019272" alt="Configuring an audience for a token in Keycloak." width="1080" height="921" data-path="images/tutorial-authorization/scope-add-audience.gif" />
177</Frame>
169![Configuring an audience for a token in Keycloak.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/scope-add-audience.gif?s=6ea9cf20c397f4c79c491c2e39019272)
178170 
179171For **Name**, use `audience-config`. Add a value for **Included Custom Audience**, set to `http://localhost:3000`. This will be the URI of our test server.
180172 
181<Warning>
182 **Not for Production**
183 
184 The audience configuration above is meant for testing. For production scenarios, additional set-up and configuration will be required to ensure that audiences are properly constrained for issued tokens. Specifically, the audience needs to be based on the resource parameter passed from the client, not a fixed value.
185</Warning>
173> [!WARNING]
174>
175> **Not for Production**
176>
177> The audience configuration above is meant for testing. For production scenarios, additional set-up and configuration will be required to ensure that audiences are properly constrained for issued tokens. Specifically, the audience needs to be based on the resource parameter passed from the client, not a fixed value.
186178 
187179Now, navigate to **Clients**, then **Client registration**, and then **Trusted Hosts**. Disable the **Client URIs Must Match** setting and add the hosts from which you're testing. You can get your current host IP by running the `ifconfig` command on Linux or macOS, or `ipconfig` on Windows. You can see the IP address you need to add by looking at the keycloak logs for a line that looks like `Failed to verify remote host : 192.168.215.1`. Check that the IP address is associated with your host. This may be for a bridge network depending on your docker setup.
188180 
189<Frame>
190 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-client.gif?s=b5d40b36a5f1ea1e818821bb8ea77f6b" alt="Setting up client registration details in Keycloak." width="1199" height="1027" data-path="images/tutorial-authorization/keycloak-client.gif" />
191</Frame>
192 
193<Warning>
194 **Getting the Host**
195 
196 If you are running Keycloak from a container, you will also be able to see the host IP from the Terminal in the container logs.
197</Warning>
181![Setting up client registration details in Keycloak.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-client.gif?s=b5d40b36a5f1ea1e818821bb8ea77f6b)
182 
183> [!WARNING]
184>
185> **Getting the Host**
186>
187> If you are running Keycloak from a container, you will also be able to see the host IP from the Terminal in the container logs.
198188 
199189Lastly, we need to register a new client that we can use with the **MCP server itself** to talk to Keycloak for things like [token introspection](https://oauth.net/2/token-introspection/). To do that:
200190 
from line 198
208198 
209199When you open the client details, go to **Credentials** and take note of the **Client Secret**.
210200 
211<Frame>
212 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-client-auth.gif?s=7152c41a5746994fd399024bc4659e40" alt="Creating a new client in Keycloak." width="1200" height="1023" data-path="images/tutorial-authorization/keycloak-client-auth.gif" />
213</Frame>
214 
215<Warning>
216 **Handling Secrets**
217 
218 Never embed client credentials directly in your code. We recommend using environment variables or specialized solutions for secret storage.
219</Warning>
201![Creating a new client in Keycloak.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-client-auth.gif?s=7152c41a5746994fd399024bc4659e40)
202 
203> [!WARNING]
204>
205> **Handling Secrets**
206>
207> Never embed client credentials directly in your code. We recommend using environment variables or specialized solutions for secret storage.
220208 
221209With Keycloak configured, every time the authorization flow is triggered, your MCP server will receive a token like this:
222210 
from line 234
246234}.[Signature]
247235```
248236 
249<Warning>
250 **Embedded Audience**
251 
252 Notice the `aud` claim embedded in the token - it's currently set to be the URI of the test MCP server and it's inferred from the scope that we've previously configured. This will be important in our implementation to validate.
253</Warning>
237> [!WARNING]
238>
239> **Embedded Audience**
240>
241> Notice the `aud` claim embedded in the token - it's currently set to be the URI of the test MCP server and it's inferred from the scope that we've previously configured. This will be important in our implementation to validate.
254242 
255243### MCP Server Setup
256244 
from line 246
258246 
259247For our testing purposes, we will create an extremely simple MCP server that exposes two tools - one for addition and another for multiplication. The server will require authorization to access these.
260248 
261<Tabs>
262 <Tab title="TypeScript">
263 You can see the complete TypeScript project in the [sample repository](https://github.com/localden/min-ts-mcp-auth).
264 
265 Prior to running the code below, ensure that you have a `.env` file with the following content:
266 
267 ```env theme={null}
268 # Server host/port
269 HOST=localhost
270 PORT=3000
271 
272 # Auth server location
273 AUTH_HOST=localhost
274 AUTH_PORT=8080
275 AUTH_REALM=master
276 
277 # Keycloak OAuth client credentials
278 OAUTH_CLIENT_ID=<YOUR_SERVER_CLIENT_ID>
279 OAUTH_CLIENT_SECRET=<YOUR_SERVER_CLIENT_SECRET>
280 ```
281 
282 `OAUTH_CLIENT_ID` and `OAUTH_CLIENT_SECRET` are associated with the MCP server client we created earlier.
283 
284 In addition to implementing the MCP authorization specification, the server below also does token introspection via Keycloak to make sure that the token it receives from the client is valid. It also implements basic logging to allow you to easily diagnose any issues.
285 
286 ```typescript theme={null}
287 import "dotenv/config";
288 import express from "express";
289 import { randomUUID } from "node:crypto";
290 import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
291 import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
292 import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
293 import { z } from "zod";
294 import cors from "cors";
295 import {
296 mcpAuthMetadataRouter,
297 getOAuthProtectedResourceMetadataUrl,
298 } from "@modelcontextprotocol/sdk/server/auth/router.js";
299 import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
300 import { OAuthMetadata } from "@modelcontextprotocol/sdk/shared/auth.js";
301 import { checkResourceAllowed } from "@modelcontextprotocol/sdk/shared/auth-utils.js";
302 const CONFIG = {
303 host: process.env.HOST || "localhost",
304 port: Number(process.env.PORT) || 3000,
305 auth: {
306 host: process.env.AUTH_HOST || process.env.HOST || "localhost",
307 port: Number(process.env.AUTH_PORT) || 8080,
308 realm: process.env.AUTH_REALM || "master",
309 clientId: process.env.OAUTH_CLIENT_ID || "mcp-server",
310 clientSecret: process.env.OAUTH_CLIENT_SECRET || "",
311 },
312 };
313 
314 function createOAuthUrls() {
315 const authBaseUrl = new URL(
316 `http://${CONFIG.auth.host}:${CONFIG.auth.port}/realms/${CONFIG.auth.realm}/`,
249**TypeScript**
250 
251You can see the complete TypeScript project in the [sample repository](https://github.com/localden/min-ts-mcp-auth).
252 
253Prior to running the code below, ensure that you have a `.env` file with the following content:
254 
255```env theme={null}
256# Server host/port
257HOST=localhost
258PORT=3000
259 
260# Auth server location
261AUTH_HOST=localhost
262AUTH_PORT=8080
263AUTH_REALM=master
264 
265# Keycloak OAuth client credentials
266OAUTH_CLIENT_ID=<YOUR_SERVER_CLIENT_ID>
267OAUTH_CLIENT_SECRET=<YOUR_SERVER_CLIENT_SECRET>
268```
269 
270`OAUTH_CLIENT_ID` and `OAUTH_CLIENT_SECRET` are associated with the MCP server client we created earlier.
271 
272In addition to implementing the MCP authorization specification, the server below also does token introspection via Keycloak to make sure that the token it receives from the client is valid. It also implements basic logging to allow you to easily diagnose any issues.
273 
274```typescript theme={null}
275import "dotenv/config";
276import express from "express";
277import { randomUUID } from "node:crypto";
278import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
279import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
280import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
281import { z } from "zod";
282import cors from "cors";
283import {
284 mcpAuthMetadataRouter,
285 getOAuthProtectedResourceMetadataUrl,
286} from "@modelcontextprotocol/sdk/server/auth/router.js";
287import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
288import { OAuthMetadata } from "@modelcontextprotocol/sdk/shared/auth.js";
289import { checkResourceAllowed } from "@modelcontextprotocol/sdk/shared/auth-utils.js";
290const CONFIG = {
291 host: process.env.HOST || "localhost",
292 port: Number(process.env.PORT) || 3000,
293 auth: {
294 host: process.env.AUTH_HOST || process.env.HOST || "localhost",
295 port: Number(process.env.AUTH_PORT) || 8080,
296 realm: process.env.AUTH_REALM || "master",
297 clientId: process.env.OAUTH_CLIENT_ID || "mcp-server",
298 clientSecret: process.env.OAUTH_CLIENT_SECRET || "",
299 },
300};
301 
302function createOAuthUrls() {
303 const authBaseUrl = new URL(
304 `http://${CONFIG.auth.host}:${CONFIG.auth.port}/realms/${CONFIG.auth.realm}/`,
305 );
306 return {
307 issuer: authBaseUrl.toString(),
308 introspection_endpoint: new URL(
309 "protocol/openid-connect/token/introspect",
310 authBaseUrl,
311 ).toString(),
312 authorization_endpoint: new URL(
313 "protocol/openid-connect/auth",
314 authBaseUrl,
315 ).toString(),
316 token_endpoint: new URL(
317 "protocol/openid-connect/token",
318 authBaseUrl,
319 ).toString(),
320 };
321}
322 
323function createRequestLogger() {
324 return (req: any, res: any, next: any) => {
325 const start = Date.now();
326 res.on("finish", () => {
327 const ms = Date.now() - start;
328 console.log(
329 `${req.method} ${req.originalUrl} -> ${res.statusCode} ${ms}ms`,
317330 );
318 return {
319 issuer: authBaseUrl.toString(),
320 introspection_endpoint: new URL(
321 "protocol/openid-connect/token/introspect",
322 authBaseUrl,
323 ).toString(),
324 authorization_endpoint: new URL(
325 "protocol/openid-connect/auth",
326 authBaseUrl,
327 ).toString(),
328 token_endpoint: new URL(
329 "protocol/openid-connect/token",
330 authBaseUrl,
331 ).toString(),
332 };
331 });
332 next();
333 };
334}
335 
336const app = express();
337 
338app.use(
339 express.json({
340 verify: (req: any, _res, buf) => {
341 req.rawBody = buf?.toString() ?? "";
342 },
343 }),
344);
345 
346app.use(
347 cors({
348 origin: "*",
349 exposedHeaders: ["Mcp-Session-Id"],
350 }),
351);
352 
353app.use(createRequestLogger());
354 
355const mcpServerUrl = new URL(`http://${CONFIG.host}:${CONFIG.port}`);
356const oauthUrls = createOAuthUrls();
357 
358const oauthMetadata: OAuthMetadata = {
359 ...oauthUrls,
360 response_types_supported: ["code"],
361};
362 
363const tokenVerifier = {
364 verifyAccessToken: async (token: string) => {
365 const endpoint = oauthMetadata.introspection_endpoint;
366 
367 if (!endpoint) {
368 console.error("[auth] no introspection endpoint in metadata");
369 throw new Error("No token verification endpoint available in metadata");
333370 }
334371 
335 function createRequestLogger() {
336 return (req: any, res: any, next: any) => {
337 const start = Date.now();
338 res.on("finish", () => {
339 const ms = Date.now() - start;
340 console.log(
341 `${req.method} ${req.originalUrl} -> ${res.statusCode} ${ms}ms`,
342 );
343 });
344 next();
345 };
372 const params = new URLSearchParams({
373 token: token,
374 client_id: CONFIG.auth.clientId,
375 });
376 
377 if (CONFIG.auth.clientSecret) {
378 params.set("client_secret", CONFIG.auth.clientSecret);
346379 }
347380 
348 const app = express();
349 
350 app.use(
351 express.json({
352 verify: (req: any, _res, buf) => {
353 req.rawBody = buf?.toString() ?? "";
381 let response: Response;
382 try {
383 response = await fetch(endpoint, {
384 method: "POST",
385 headers: {
386 "Content-Type": "application/x-www-form-urlencoded",
354387 },
388 body: params.toString(),
389 });
390 } catch (e) {
391 console.error("[auth] introspection fetch threw", e);
392 throw e;
393 }
394 
395 if (!response.ok) {
396 const txt = await response.text();
397 console.error("[auth] introspection non-OK", { status: response.status });
398 
399 try {
400 const obj = JSON.parse(txt);
401 console.log(JSON.stringify(obj, null, 2));
402 } catch {
403 console.error(txt);
404 }
405 throw new Error(`Invalid or expired token: ${txt}`);
406 }
407 
408 let data: any;
409 try {
410 data = await response.json();
411 } catch (e) {
412 const txt = await response.text();
413 console.error("[auth] failed to parse introspection JSON", {
414 error: String(e),
415 body: txt,
416 });
417 throw e;
418 }
419 
420 if (data.active === false) {
421 throw new Error("Inactive token");
422 }
423 
424 if (!data.aud) {
425 throw new Error("Resource indicator (aud) missing");
426 }
427 
428 const audiences: string[] = Array.isArray(data.aud) ? data.aud : [data.aud];
429 const allowed = audiences.some((a) =>
430 checkResourceAllowed({
431 requestedResource: a,
432 configuredResource: mcpServerUrl,
355433 }),
356434 );
357 
358 app.use(
359 cors({
360 origin: "*",
361 exposedHeaders: ["Mcp-Session-Id"],
362 }),
363 );
364 
365 app.use(createRequestLogger());
366 
367 const mcpServerUrl = new URL(`http://${CONFIG.host}:${CONFIG.port}`);
368 const oauthUrls = createOAuthUrls();
369 
370 const oauthMetadata: OAuthMetadata = {
371 ...oauthUrls,
372 response_types_supported: ["code"],
435 if (!allowed) {
436 throw new Error(
437 `None of the provided audiences are allowed. Expected ${mcpServerUrl}, got: ${audiences.join(", ")}`,
438 );
439 }
440 
441 return {
442 token,
443 clientId: data.client_id,
444 scopes: data.scope ? data.scope.split(" ") : [],
445 expiresAt: data.exp,
373446 };
374 
375 const tokenVerifier = {
376 verifyAccessToken: async (token: string) => {
377 const endpoint = oauthMetadata.introspection_endpoint;
378 
379 if (!endpoint) {
380 console.error("[auth] no introspection endpoint in metadata");
381 throw new Error("No token verification endpoint available in metadata");
447 },
448};
449app.use(
450 mcpAuthMetadataRouter({
451 oauthMetadata,
452 resourceServerUrl: mcpServerUrl,
453 scopesSupported: ["mcp:tools"],
454 resourceName: "MCP Demo Server",
455 }),
456);
457 
458const authMiddleware = requireBearerAuth({
459 verifier: tokenVerifier,
460 requiredScopes: [],
461 resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl),
462});
463 
464const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {};
465 
466function createMcpServer() {
467 const server = new McpServer({
468 name: "example-server",
469 version: "1.0.0",
470 });
471 
472 server.registerTool(
473 "add",
474 {
475 title: "Addition Tool",
476 description: "Add two numbers together",
477 inputSchema: {
478 a: z.number().describe("First number to add"),
479 b: z.number().describe("Second number to add"),
480 },
481 },
482 async ({ a, b }) => ({
483 content: [{ type: "text", text: `${a} + ${b} = ${a + b}` }],
484 }),
485 );
486 
487 server.registerTool(
488 "multiply",
489 {
490 title: "Multiplication Tool",
491 description: "Multiply two numbers together",
492 inputSchema: {
493 x: z.number().describe("First number to multiply"),
494 y: z.number().describe("Second number to multiply"),
495 },
496 },
497 async ({ x, y }) => ({
498 content: [{ type: "text", text: `${x} × ${y} = ${x * y}` }],
499 }),
500 );
501 
502 return server;
503}
504 
505const mcpPostHandler = async (req: express.Request, res: express.Response) => {
506 const sessionId = req.headers["mcp-session-id"] as string | undefined;
507 let transport: StreamableHTTPServerTransport;
508 
509 if (sessionId && transports[sessionId]) {
510 transport = transports[sessionId];
511 } else if (!sessionId && isInitializeRequest(req.body)) {
512 transport = new StreamableHTTPServerTransport({
513 sessionIdGenerator: () => randomUUID(),
514 onsessioninitialized: (sessionId) => {
515 transports[sessionId] = transport;
516 },
517 });
518 
519 transport.onclose = () => {
520 if (transport.sessionId) {
521 delete transports[transport.sessionId];
522 }
523 };
524 
525 const server = createMcpServer();
526 await server.connect(transport);
527 } else {
528 res.status(400).json({
529 jsonrpc: "2.0",
530 error: {
531 code: -32000,
532 message: "Bad Request: No valid session ID provided",
533 },
534 id: null,
535 });
536 return;
537 }
538 
539 await transport.handleRequest(req, res, req.body);
540};
541 
542const handleSessionRequest = async (
543 req: express.Request,
544 res: express.Response,
545) => {
546 const sessionId = req.headers["mcp-session-id"] as string | undefined;
547 if (!sessionId || !transports[sessionId]) {
548 res.status(400).send("Invalid or missing session ID");
549 return;
550 }
551 
552 const transport = transports[sessionId];
553 await transport.handleRequest(req, res);
554};
555 
556app.post("/", authMiddleware, mcpPostHandler);
557app.get("/", authMiddleware, handleSessionRequest);
558app.delete("/", authMiddleware, handleSessionRequest);
559 
560app.listen(CONFIG.port, CONFIG.host, () => {
561 console.log(`🚀 MCP Server running on ${mcpServerUrl.origin}`);
562 console.log(`📡 MCP endpoint available at ${mcpServerUrl.origin}`);
563 console.log(
564 `🔐 OAuth metadata available at ${getOAuthProtectedResourceMetadataUrl(mcpServerUrl)}`,
565 );
566});
567```
568 
569When you run the server, you can add it to your MCP client, such as Visual Studio Code, by providing the MCP server endpoint.
570 
571For more details about implementing MCP servers in TypeScript, refer to the [TypeScript SDK documentation](https://github.com/modelcontextprotocol/typescript-sdk).
572 
573**Python**
574 
575You can see the complete Python project in the [sample repository](https://github.com/modelcontextprotocol/python-sdk/tree/main/examples/servers/simple-auth).
576 
577To simplify our authorization interaction, in Python scenarios we rely on [FastMCP](https://gofastmcp.com/getting-started/welcome). Many of the conventions around authorization, like the endpoints and token validation logic, are consistent across languages, but some offer simpler ways of integrating them in production scenarios.
578 
579Prior to writing the actual server, we need to set up our configuration in `config.py` - the contents are entirely based on your local server setup:
580 
581```python theme={null}
582"""Configuration settings for the MCP auth server."""
583 
584import os
585from typing import Optional
586 
587 
588class Config:
589 """Configuration class that loads from environment variables with sensible defaults."""
590 
591 # Server settings
592 HOST: str = os.getenv("HOST", "localhost")
593 PORT: int = int(os.getenv("PORT", "3000"))
594 
595 # Auth server settings
596 AUTH_HOST: str = os.getenv("AUTH_HOST", "localhost")
597 AUTH_PORT: int = int(os.getenv("AUTH_PORT", "8080"))
598 AUTH_REALM: str = os.getenv("AUTH_REALM", "master")
599 
600 # OAuth client settings
601 OAUTH_CLIENT_ID: str = os.getenv("OAUTH_CLIENT_ID", "mcp-server")
602 OAUTH_CLIENT_SECRET: str = os.getenv("OAUTH_CLIENT_SECRET", "UO3rmozkFFkXr0QxPTkzZ0LMXDidIikB")
603 
604 # Server settings
605 MCP_SCOPE: str = os.getenv("MCP_SCOPE", "mcp:tools")
606 OAUTH_STRICT: bool = os.getenv("OAUTH_STRICT", "false").lower() in ("true", "1", "yes")
607 TRANSPORT: str = os.getenv("TRANSPORT", "streamable-http")
608 
609 @property
610 def server_url(self) -> str:
611 """Build the server URL."""
612 return f"http://{self.HOST}:{self.PORT}"
613 
614 @property
615 def auth_base_url(self) -> str:
616 """Build the auth server base URL."""
617 return f"http://{self.AUTH_HOST}:{self.AUTH_PORT}/realms/{self.AUTH_REALM}/"
618 
619 def validate(self) -> None:
620 """Validate configuration."""
621 if self.TRANSPORT not in ["sse", "streamable-http"]:
622 raise ValueError(f"Invalid transport: {self.TRANSPORT}. Must be 'sse' or 'streamable-http'")
623 
624 
625# Global configuration instance
626config = Config()
627 
628```
629 
630The server implementation is as follows:
631 
632```python theme={null}
633import datetime
634import logging
635from typing import Any
636 
637from pydantic import AnyHttpUrl
638 
639from mcp.server.auth.settings import AuthSettings
640from mcp.server.fastmcp.server import FastMCP
641 
642from .config import config
643from .token_verifier import IntrospectionTokenVerifier
644 
645logger = logging.getLogger(__name__)
646 
647 
648def create_oauth_urls() -> dict[str, str]:
649 """Create OAuth URLs based on configuration (Keycloak-style)."""
650 from urllib.parse import urljoin
651 
652 auth_base_url = config.auth_base_url
653 
654 return {
655 "issuer": auth_base_url,
656 "introspection_endpoint": urljoin(auth_base_url, "protocol/openid-connect/token/introspect"),
657 "authorization_endpoint": urljoin(auth_base_url, "protocol/openid-connect/auth"),
658 "token_endpoint": urljoin(auth_base_url, "protocol/openid-connect/token"),
659 }
660 
661 
662def create_server() -> FastMCP:
663 """Create and configure the FastMCP server."""
664 
665 config.validate()
666 
667 oauth_urls = create_oauth_urls()
668 
669 token_verifier = IntrospectionTokenVerifier(
670 introspection_endpoint=oauth_urls["introspection_endpoint"],
671 server_url=config.server_url,
672 client_id=config.OAUTH_CLIENT_ID,
673 client_secret=config.OAUTH_CLIENT_SECRET,
674 )
675 
676 app = FastMCP(
677 name="MCP Resource Server",
678 instructions="Resource Server that validates tokens via Authorization Server introspection",
679 host=config.HOST,
680 port=config.PORT,
681 debug=True,
682 streamable_http_path="/",
683 token_verifier=token_verifier,
684 auth=AuthSettings(
685 issuer_url=AnyHttpUrl(oauth_urls["issuer"]),
686 required_scopes=[config.MCP_SCOPE],
687 resource_server_url=AnyHttpUrl(config.server_url),
688 ),
689 )
690 
691 @app.tool()
692 async def add_numbers(a: float, b: float) -> dict[str, Any]:
693 """
694 Add two numbers together.
695 This tool demonstrates basic arithmetic operations with OAuth authentication.
696 
697 Args:
698 a: The first number to add
699 b: The second number to add
700 """
701 result = a + b
702 return {
703 "operation": "addition",
704 "operand_a": a,
705 "operand_b": b,
706 "result": result,
707 "timestamp": datetime.datetime.now().isoformat()
382708 }
383709 
384 const params = new URLSearchParams({
385 token: token,
386 client_id: CONFIG.auth.clientId,
387 });
388 
389 if (CONFIG.auth.clientSecret) {
390 params.set("client_secret", CONFIG.auth.clientSecret);
710 @app.tool()
711 async def multiply_numbers(x: float, y: float) -> dict[str, Any]:
712 """
713 Multiply two numbers together.
714 This tool demonstrates basic arithmetic operations with OAuth authentication.
715 
716 Args:
717 x: The first number to multiply
718 y: The second number to multiply
719 """
720 result = x * y
721 return {
722 "operation": "multiplication",
723 "operand_x": x,
724 "operand_y": y,
725 "result": result,
726 "timestamp": datetime.datetime.now().isoformat()
391727 }
392728 
393 let response: Response;
394 try {
395 response = await fetch(endpoint, {
396 method: "POST",
397 headers: {
398 "Content-Type": "application/x-www-form-urlencoded",
399 },
400 body: params.toString(),
401 });
402 } catch (e) {
403 console.error("[auth] introspection fetch threw", e);
404 throw e;
729 return app
730 
731 
732def main() -> int:
733 """
734 Run the MCP Resource Server.
735 
736 This server:
737 - Provides RFC 9728 Protected Resource Metadata
738 - Validates tokens via Authorization Server introspection
739 - Serves MCP tools requiring authentication
740 
741 Configuration is loaded from config.py and environment variables.
742 """
743 logging.basicConfig(level=logging.INFO)
744 
745 try:
746 config.validate()
747 oauth_urls = create_oauth_urls()
748 
749 except ValueError as e:
750 logger.error("Configuration error: %s", e)
751 return 1
752 
753 try:
754 mcp_server = create_server()
755 
756 logger.info("Starting MCP Server on %s:%s", config.HOST, config.PORT)
757 logger.info("Authorization Server: %s", oauth_urls["issuer"])
758 logger.info("Transport: %s", config.TRANSPORT)
759 
760 mcp_server.run(transport=config.TRANSPORT)
761 return 0
762 
763 except Exception:
764 logger.exception("Server error")
765 return 1
766 
767 
768if __name__ == "__main__":
769 exit(main())
770```
771 
772Lastly, the token verification logic is delegated entirely to `token_verifier.py`, ensuring that we can use the Keycloak introspection endpoint to verify the validity of any credential artifacts
773 
774```python theme={null}
775"""Token verifier implementation using OAuth 2.0 Token Introspection (RFC 7662)."""
776 
777import logging
778from typing import Any
779 
780from mcp.server.auth.provider import AccessToken, TokenVerifier
781from mcp.shared.auth_utils import check_resource_allowed, resource_url_from_server_url
782 
783logger = logging.getLogger(__name__)
784 
785 
786class IntrospectionTokenVerifier(TokenVerifier):
787 """Token verifier that uses OAuth 2.0 Token Introspection (RFC 7662).
788 """
789 
790 def __init__(
791 self,
792 introspection_endpoint: str,
793 server_url: str,
794 client_id: str,
795 client_secret: str,
796 ):
797 self.introspection_endpoint = introspection_endpoint
798 self.server_url = server_url
799 self.client_id = client_id
800 self.client_secret = client_secret
801 self.resource_url = resource_url_from_server_url(server_url)
802 
803 async def verify_token(self, token: str) -> AccessToken | None:
804 """Verify token via introspection endpoint."""
805 import httpx
806 
807 if not self.introspection_endpoint.startswith(("https://", "http://localhost", "http://127.0.0.1")):
808 return None
809 
810 timeout = httpx.Timeout(10.0, connect=5.0)
811 limits = httpx.Limits(max_connections=10, max_keepalive_connections=5)
812 
813 async with httpx.AsyncClient(
814 timeout=timeout,
815 limits=limits,
816 verify=True,
817 ) as client:
818 try:
819 form_data = {
820 "token": token,
821 "client_id": self.client_id,
822 "client_secret": self.client_secret,
823 }
824 headers = {"Content-Type": "application/x-www-form-urlencoded"}
825 
826 response = await client.post(
827 self.introspection_endpoint,
828 data=form_data,
829 headers=headers,
830 )
831 
832 if response.status_code != 200:
833 return None
834 
835 data = response.json()
836 if not data.get("active", False):
837 return None
838 
839 if not self._validate_resource(data):
840 return None
841 
842 return AccessToken(
843 token=token,
844 client_id=data.get("client_id", "unknown"),
845 scopes=data.get("scope", "").split() if data.get("scope") else [],
846 expires_at=data.get("exp"),
847 resource=data.get("aud"), # Include resource in token
848 )
849 
850 except Exception as e:
851 return None
852 
853 def _validate_resource(self, token_data: dict[str, Any]) -> bool:
854 """Validate token was issued for this resource server.
855 
856 Rules:
857 - Reject if 'aud' missing.
858 - Accept if any audience entry matches the derived resource URL.
859 - Supports string or list forms per JWT spec.
860 """
861 if not self.server_url or not self.resource_url:
862 return False
863 
864 aud: list[str] | str | None = token_data.get("aud")
865 if isinstance(aud, list):
866 return any(self._is_valid_resource(a) for a in aud)
867 if isinstance(aud, str):
868 return self._is_valid_resource(aud)
869 return False
870 
871 def _is_valid_resource(self, resource: str) -> bool:
872 """Check if the given resource matches our server."""
873 return check_resource_allowed(self.resource_url, resource)
874```
875 
876For more details, see the [Python SDK documentation](https://github.com/modelcontextprotocol/python-sdk).
877 
878**C#**
879 
880You can see the complete C# project in the [sample repository](https://github.com/localden/min-cs-mcp-auth).
881 
882To set up authorization in your MCP server using the MCP C# SDK, you can lean on the standard ASP.NET Core builder pattern. Instead of using the introspection endpoint provided by Keycloak, we will use built-in ASP.NET Core capabilities for token validation.
883 
884```csharp theme={null}
885using Microsoft.AspNetCore.Authentication.JwtBearer;
886using Microsoft.IdentityModel.Tokens;
887using ModelContextProtocol.AspNetCore.Authentication;
888using ProtectedMcpServer.Tools;
889using System.Security.Claims;
890 
891var builder = WebApplication.CreateBuilder(args);
892 
893var serverUrl = "http://localhost:3000/";
894var authorizationServerUrl = "http://localhost:8080/realms/master/";
895 
896builder.Services.AddAuthentication(options =>
897{
898 options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;
899 options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
900})
901.AddJwtBearer(options =>
902{
903 options.Authority = authorizationServerUrl;
904 var normalizedServerAudience = serverUrl.TrimEnd('/');
905 options.TokenValidationParameters = new TokenValidationParameters
906 {
907 ValidIssuer = authorizationServerUrl,
908 ValidAudiences = new[] { normalizedServerAudience, serverUrl },
909 AudienceValidator = (audiences, securityToken, validationParameters) =>
910 {
911 if (audiences == null) return false;
912 foreach (var aud in audiences)
913 {
914 if (string.Equals(aud.TrimEnd('/'), normalizedServerAudience, StringComparison.OrdinalIgnoreCase))
915 {
916 return true;
917 }
918 }
919 return false;
405920 }
406 
407 if (!response.ok) {
408 const txt = await response.text();
409 console.error("[auth] introspection non-OK", { status: response.status });
410 
411 try {
412 const obj = JSON.parse(txt);
413 console.log(JSON.stringify(obj, null, 2));
414 } catch {
415 console.error(txt);
416 }
417 throw new Error(`Invalid or expired token: ${txt}`);
418 }
419 
420 let data: any;
421 try {
422 data = await response.json();
423 } catch (e) {
424 const txt = await response.text();
425 console.error("[auth] failed to parse introspection JSON", {
426 error: String(e),
427 body: txt,
428 });
429 throw e;
430 }
431 
432 if (data.active === false) {
433 throw new Error("Inactive token");
434 }
435 
436 if (!data.aud) {
437 throw new Error("Resource indicator (aud) missing");
438 }
439 
440 const audiences: string[] = Array.isArray(data.aud) ? data.aud : [data.aud];
441 const allowed = audiences.some((a) =>
442 checkResourceAllowed({
443 requestedResource: a,
444 configuredResource: mcpServerUrl,
445 }),
446 );
447 if (!allowed) {
448 throw new Error(
449 `None of the provided audiences are allowed. Expected ${mcpServerUrl}, got: ${audiences.join(", ")}`,
450 );
451 }
452 
453 return {
454 token,
455 clientId: data.client_id,
456 scopes: data.scope ? data.scope.split(" ") : [],
457 expiresAt: data.exp,
458 };
459 },
460921 };
461 app.use(
462 mcpAuthMetadataRouter({
463 oauthMetadata,
464 resourceServerUrl: mcpServerUrl,
465 scopesSupported: ["mcp:tools"],
466 resourceName: "MCP Demo Server",
467 }),
468 );
469 
470 const authMiddleware = requireBearerAuth({
471 verifier: tokenVerifier,
472 requiredScopes: [],
473 resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl),
474 });
475 
476 const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {};
477 
478 function createMcpServer() {
479 const server = new McpServer({
480 name: "example-server",
481 version: "1.0.0",
482 });
483 
484 server.registerTool(
485 "add",
922 
923 options.RequireHttpsMetadata = false; // Set to true in production
924 
925 options.Events = new JwtBearerEvents
926 {
927 OnTokenValidated = context =>
486928 {
487 title: "Addition Tool",
488 description: "Add two numbers together",
489 inputSchema: {
490 a: z.number().describe("First number to add"),
491 b: z.number().describe("Second number to add"),
492 },
929 var name = context.Principal?.Identity?.Name ?? "unknown";
930 var email = context.Principal?.FindFirstValue("preferred_username") ?? "unknown";
931 Console.WriteLine($"Token validated for: {name} ({email})");
932 return Task.CompletedTask;
493933 },
494 async ({ a, b }) => ({
495 content: [{ type: "text", text: `${a} + ${b} = ${a + b}` }],
496 }),
497 );
498 
499 server.registerTool(
500 "multiply",
934 OnAuthenticationFailed = context =>
501935 {
502 title: "Multiplication Tool",
503 description: "Multiply two numbers together",
504 inputSchema: {
505 x: z.number().describe("First number to multiply"),
506 y: z.number().describe("Second number to multiply"),
507 },
936 Console.WriteLine($"Authentication failed: {context.Exception.Message}");
937 return Task.CompletedTask;
508938 },
509 async ({ x, y }) => ({
510 content: [{ type: "text", text: `${x} × ${y} = ${x * y}` }],
511 }),
512 );
513 
514 return server;
515 }
516 
517 const mcpPostHandler = async (req: express.Request, res: express.Response) => {
518 const sessionId = req.headers["mcp-session-id"] as string | undefined;
519 let transport: StreamableHTTPServerTransport;
520 
521 if (sessionId && transports[sessionId]) {
522 transport = transports[sessionId];
523 } else if (!sessionId && isInitializeRequest(req.body)) {
524 transport = new StreamableHTTPServerTransport({
525 sessionIdGenerator: () => randomUUID(),
526 onsessioninitialized: (sessionId) => {
527 transports[sessionId] = transport;
528 },
529 });
530 
531 transport.onclose = () => {
532 if (transport.sessionId) {
533 delete transports[transport.sessionId];
534 }
535 };
536 
537 const server = createMcpServer();
538 await server.connect(transport);
539 } else {
540 res.status(400).json({
541 jsonrpc: "2.0",
542 error: {
543 code: -32000,
544 message: "Bad Request: No valid session ID provided",
545 },
546 id: null,
547 });
548 return;
549 }
550 
551 await transport.handleRequest(req, res, req.body);
552939 };
553 
554 const handleSessionRequest = async (
555 req: express.Request,
556 res: express.Response,
557 ) => {
558 const sessionId = req.headers["mcp-session-id"] as string | undefined;
559 if (!sessionId || !transports[sessionId]) {
560 res.status(400).send("Invalid or missing session ID");
561 return;
562 }
563 
564 const transport = transports[sessionId];
565 await transport.handleRequest(req, res);
940})
941.AddMcp(options =>
942{
943 options.ResourceMetadata = new()
944 {
945 Resource = new Uri(serverUrl),
946 ResourceDocumentation = new Uri("https://docs.example.com/api/math"),
947 AuthorizationServers = { new Uri(authorizationServerUrl) },
948 ScopesSupported = ["mcp:tools"]
566949 };
567 
568 app.post("/", authMiddleware, mcpPostHandler);
569 app.get("/", authMiddleware, handleSessionRequest);
570 app.delete("/", authMiddleware, handleSessionRequest);
571 
572 app.listen(CONFIG.port, CONFIG.host, () => {
573 console.log(`🚀 MCP Server running on ${mcpServerUrl.origin}`);
574 console.log(`📡 MCP endpoint available at ${mcpServerUrl.origin}`);
575 console.log(
576 `🔐 OAuth metadata available at ${getOAuthProtectedResourceMetadataUrl(mcpServerUrl)}`,
577 );
578 });
579 ```
580 
581 When you run the server, you can add it to your MCP client, such as Visual Studio Code, by providing the MCP server endpoint.
582 
583 For more details about implementing MCP servers in TypeScript, refer to the [TypeScript SDK documentation](https://github.com/modelcontextprotocol/typescript-sdk).
584 </Tab>
585 
586 <Tab title="Python">
587 You can see the complete Python project in the [sample repository](https://github.com/modelcontextprotocol/python-sdk/tree/main/examples/servers/simple-auth).
588 
589 To simplify our authorization interaction, in Python scenarios we rely on [FastMCP](https://gofastmcp.com/getting-started/welcome). Many of the conventions around authorization, like the endpoints and token validation logic, are consistent across languages, but some offer simpler ways of integrating them in production scenarios.
590 
591 Prior to writing the actual server, we need to set up our configuration in `config.py` - the contents are entirely based on your local server setup:
592 
593 ```python theme={null}
594 """Configuration settings for the MCP auth server."""
595 
596 import os
597 from typing import Optional
598 
599 
600 class Config:
601 """Configuration class that loads from environment variables with sensible defaults."""
602 
603 # Server settings
604 HOST: str = os.getenv("HOST", "localhost")
605 PORT: int = int(os.getenv("PORT", "3000"))
606 
607 # Auth server settings
608 AUTH_HOST: str = os.getenv("AUTH_HOST", "localhost")
609 AUTH_PORT: int = int(os.getenv("AUTH_PORT", "8080"))
610 AUTH_REALM: str = os.getenv("AUTH_REALM", "master")
611 
612 # OAuth client settings
613 OAUTH_CLIENT_ID: str = os.getenv("OAUTH_CLIENT_ID", "mcp-server")
614 OAUTH_CLIENT_SECRET: str = os.getenv("OAUTH_CLIENT_SECRET", "UO3rmozkFFkXr0QxPTkzZ0LMXDidIikB")
615 
616 # Server settings
617 MCP_SCOPE: str = os.getenv("MCP_SCOPE", "mcp:tools")
618 OAUTH_STRICT: bool = os.getenv("OAUTH_STRICT", "false").lower() in ("true", "1", "yes")
619 TRANSPORT: str = os.getenv("TRANSPORT", "streamable-http")
620 
621 @property
622 def server_url(self) -> str:
623 """Build the server URL."""
624 return f"http://{self.HOST}:{self.PORT}"
625 
626 @property
627 def auth_base_url(self) -> str:
628 """Build the auth server base URL."""
629 return f"http://{self.AUTH_HOST}:{self.AUTH_PORT}/realms/{self.AUTH_REALM}/"
630 
631 def validate(self) -> None:
632 """Validate configuration."""
633 if self.TRANSPORT not in ["sse", "streamable-http"]:
634 raise ValueError(f"Invalid transport: {self.TRANSPORT}. Must be 'sse' or 'streamable-http'")
635 
636 
637 # Global configuration instance
638 config = Config()
639 
640 ```
641 
642 The server implementation is as follows:
643 
644 ```python theme={null}
645 import datetime
646 import logging
647 from typing import Any
648 
649 from pydantic import AnyHttpUrl
650 
651 from mcp.server.auth.settings import AuthSettings
652 from mcp.server.fastmcp.server import FastMCP
653 
654 from .config import config
655 from .token_verifier import IntrospectionTokenVerifier
656 
657 logger = logging.getLogger(__name__)
658 
659 
660 def create_oauth_urls() -> dict[str, str]:
661 """Create OAuth URLs based on configuration (Keycloak-style)."""
662 from urllib.parse import urljoin
663 
664 auth_base_url = config.auth_base_url
665 
666 return {
667 "issuer": auth_base_url,
668 "introspection_endpoint": urljoin(auth_base_url, "protocol/openid-connect/token/introspect"),
669 "authorization_endpoint": urljoin(auth_base_url, "protocol/openid-connect/auth"),
670 "token_endpoint": urljoin(auth_base_url, "protocol/openid-connect/token"),
671 }
672 
673 
674 def create_server() -> FastMCP:
675 """Create and configure the FastMCP server."""
676 
677 config.validate()
678 
679 oauth_urls = create_oauth_urls()
680 
681 token_verifier = IntrospectionTokenVerifier(
682 introspection_endpoint=oauth_urls["introspection_endpoint"],
683 server_url=config.server_url,
684 client_id=config.OAUTH_CLIENT_ID,
685 client_secret=config.OAUTH_CLIENT_SECRET,
686 )
687 
688 app = FastMCP(
689 name="MCP Resource Server",
690 instructions="Resource Server that validates tokens via Authorization Server introspection",
691 host=config.HOST,
692 port=config.PORT,
693 debug=True,
694 streamable_http_path="/",
695 token_verifier=token_verifier,
696 auth=AuthSettings(
697 issuer_url=AnyHttpUrl(oauth_urls["issuer"]),
698 required_scopes=[config.MCP_SCOPE],
699 resource_server_url=AnyHttpUrl(config.server_url),
700 ),
701 )
702 
703 @app.tool()
704 async def add_numbers(a: float, b: float) -> dict[str, Any]:
705 """
706 Add two numbers together.
707 This tool demonstrates basic arithmetic operations with OAuth authentication.
708 
709 Args:
710 a: The first number to add
711 b: The second number to add
712 """
713 result = a + b
714 return {
715 "operation": "addition",
716 "operand_a": a,
717 "operand_b": b,
718 "result": result,
719 "timestamp": datetime.datetime.now().isoformat()
720 }
721 
722 @app.tool()
723 async def multiply_numbers(x: float, y: float) -> dict[str, Any]:
724 """
725 Multiply two numbers together.
726 This tool demonstrates basic arithmetic operations with OAuth authentication.
727 
728 Args:
729 x: The first number to multiply
730 y: The second number to multiply
731 """
732 result = x * y
733 return {
734 "operation": "multiplication",
735 "operand_x": x,
736 "operand_y": y,
737 "result": result,
738 "timestamp": datetime.datetime.now().isoformat()
739 }
740 
741 return app
742 
743 
744 def main() -> int:
745 """
746 Run the MCP Resource Server.
747 
748 This server:
749 - Provides RFC 9728 Protected Resource Metadata
750 - Validates tokens via Authorization Server introspection
751 - Serves MCP tools requiring authentication
752 
753 Configuration is loaded from config.py and environment variables.
754 """
755 logging.basicConfig(level=logging.INFO)
756 
757 try:
758 config.validate()
759 oauth_urls = create_oauth_urls()
760 
761 except ValueError as e:
762 logger.error("Configuration error: %s", e)
763 return 1
764 
765 try:
766 mcp_server = create_server()
767 
768 logger.info("Starting MCP Server on %s:%s", config.HOST, config.PORT)
769 logger.info("Authorization Server: %s", oauth_urls["issuer"])
770 logger.info("Transport: %s", config.TRANSPORT)
771 
772 mcp_server.run(transport=config.TRANSPORT)
773 return 0
774 
775 except Exception:
776 logger.exception("Server error")
777 return 1
778 
779 
780 if __name__ == "__main__":
781 exit(main())
782 ```
783 
784 Lastly, the token verification logic is delegated entirely to `token_verifier.py`, ensuring that we can use the Keycloak introspection endpoint to verify the validity of any credential artifacts
785 
786 ```python theme={null}
787 """Token verifier implementation using OAuth 2.0 Token Introspection (RFC 7662)."""
788 
789 import logging
790 from typing import Any
791 
792 from mcp.server.auth.provider import AccessToken, TokenVerifier
793 from mcp.shared.auth_utils import check_resource_allowed, resource_url_from_server_url
794 
795 logger = logging.getLogger(__name__)
796 
797 
798 class IntrospectionTokenVerifier(TokenVerifier):
799 """Token verifier that uses OAuth 2.0 Token Introspection (RFC 7662).
800 """
801 
802 def __init__(
803 self,
804 introspection_endpoint: str,
805 server_url: str,
806 client_id: str,
807 client_secret: str,
808 ):
809 self.introspection_endpoint = introspection_endpoint
810 self.server_url = server_url
811 self.client_id = client_id
812 self.client_secret = client_secret
813 self.resource_url = resource_url_from_server_url(server_url)
814 
815 async def verify_token(self, token: str) -> AccessToken | None:
816 """Verify token via introspection endpoint."""
817 import httpx
818 
819 if not self.introspection_endpoint.startswith(("https://", "http://localhost", "http://127.0.0.1")):
820 return None
821 
822 timeout = httpx.Timeout(10.0, connect=5.0)
823 limits = httpx.Limits(max_connections=10, max_keepalive_connections=5)
824 
825 async with httpx.AsyncClient(
826 timeout=timeout,
827 limits=limits,
828 verify=True,
829 ) as client:
830 try:
831 form_data = {
832 "token": token,
833 "client_id": self.client_id,
834 "client_secret": self.client_secret,
835 }
836 headers = {"Content-Type": "application/x-www-form-urlencoded"}
837 
838 response = await client.post(
839 self.introspection_endpoint,
840 data=form_data,
841 headers=headers,
842 )
843 
844 if response.status_code != 200:
845 return None
846 
847 data = response.json()
848 if not data.get("active", False):
849 return None
850 
851 if not self._validate_resource(data):
852 return None
853 
854 return AccessToken(
855 token=token,
856 client_id=data.get("client_id", "unknown"),
857 scopes=data.get("scope", "").split() if data.get("scope") else [],
858 expires_at=data.get("exp"),
859 resource=data.get("aud"), # Include resource in token
860 )
861 
862 except Exception as e:
863 return None
864 
865 def _validate_resource(self, token_data: dict[str, Any]) -> bool:
866 """Validate token was issued for this resource server.
867 
868 Rules:
869 - Reject if 'aud' missing.
870 - Accept if any audience entry matches the derived resource URL.
871 - Supports string or list forms per JWT spec.
872 """
873 if not self.server_url or not self.resource_url:
874 return False
875 
876 aud: list[str] | str | None = token_data.get("aud")
877 if isinstance(aud, list):
878 return any(self._is_valid_resource(a) for a in aud)
879 if isinstance(aud, str):
880 return self._is_valid_resource(aud)
881 return False
882 
883 def _is_valid_resource(self, resource: str) -> bool:
884 """Check if the given resource matches our server."""
885 return check_resource_allowed(self.resource_url, resource)
886 ```
887 
888 For more details, see the [Python SDK documentation](https://github.com/modelcontextprotocol/python-sdk).
889 </Tab>
890 
891 <Tab title="C#">
892 You can see the complete C# project in the [sample repository](https://github.com/localden/min-cs-mcp-auth).
893 
894 To set up authorization in your MCP server using the MCP C# SDK, you can lean on the standard ASP.NET Core builder pattern. Instead of using the introspection endpoint provided by Keycloak, we will use built-in ASP.NET Core capabilities for token validation.
895 
896 ```csharp theme={null}
897 using Microsoft.AspNetCore.Authentication.JwtBearer;
898 using Microsoft.IdentityModel.Tokens;
899 using ModelContextProtocol.AspNetCore.Authentication;
900 using ProtectedMcpServer.Tools;
901 using System.Security.Claims;
902 
903 var builder = WebApplication.CreateBuilder(args);
904 
905 var serverUrl = "http://localhost:3000/";
906 var authorizationServerUrl = "http://localhost:8080/realms/master/";
907 
908 builder.Services.AddAuthentication(options =>
909 {
910 options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;
911 options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
912 })
913 .AddJwtBearer(options =>
914 {
915 options.Authority = authorizationServerUrl;
916 var normalizedServerAudience = serverUrl.TrimEnd('/');
917 options.TokenValidationParameters = new TokenValidationParameters
918 {
919 ValidIssuer = authorizationServerUrl,
920 ValidAudiences = new[] { normalizedServerAudience, serverUrl },
921 AudienceValidator = (audiences, securityToken, validationParameters) =>
922 {
923 if (audiences == null) return false;
924 foreach (var aud in audiences)
925 {
926 if (string.Equals(aud.TrimEnd('/'), normalizedServerAudience, StringComparison.OrdinalIgnoreCase))
927 {
928 return true;
929 }
930 }
931 return false;
932 }
933 };
934 
935 options.RequireHttpsMetadata = false; // Set to true in production
936 
937 options.Events = new JwtBearerEvents
938 {
939 OnTokenValidated = context =>
940 {
941 var name = context.Principal?.Identity?.Name ?? "unknown";
942 var email = context.Principal?.FindFirstValue("preferred_username") ?? "unknown";
943 Console.WriteLine($"Token validated for: {name} ({email})");
944 return Task.CompletedTask;
945 },
946 OnAuthenticationFailed = context =>
947 {
948 Console.WriteLine($"Authentication failed: {context.Exception.Message}");
949 return Task.CompletedTask;
950 },
951 };
952 })
953 .AddMcp(options =>
954 {
955 options.ResourceMetadata = new()
956 {
957 Resource = new Uri(serverUrl),
958 ResourceDocumentation = new Uri("https://docs.example.com/api/math"),
959 AuthorizationServers = { new Uri(authorizationServerUrl) },
960 ScopesSupported = ["mcp:tools"]
961 };
962 });
963 
964 builder.Services.AddAuthorization();
965 
966 builder.Services.AddHttpContextAccessor();
967 builder.Services.AddMcpServer()
968 .WithTools<MathTools>()
969 .WithHttpTransport();
970 
971 var app = builder.Build();
972 
973 app.UseAuthentication();
974 app.UseAuthorization();
975 
976 app.MapMcp().RequireAuthorization();
977 
978 Console.WriteLine($"Starting MCP server with authorization at {serverUrl}");
979 Console.WriteLine($"Using Keycloak server at {authorizationServerUrl}");
980 Console.WriteLine($"Protected Resource Metadata URL: {serverUrl}.well-known/oauth-protected-resource");
981 Console.WriteLine("Exposed Math tools: Add, Multiply");
982 Console.WriteLine("Press Ctrl+C to stop the server");
983 
984 app.Run(serverUrl);
985 ```
986 
987 For more details, see the [C# SDK documentation](https://github.com/modelcontextprotocol/csharp-sdk).
988 </Tab>
989</Tabs>
950});
951 
952builder.Services.AddAuthorization();
953 
954builder.Services.AddHttpContextAccessor();
955builder.Services.AddMcpServer()
956 .WithTools<MathTools>()
957 .WithHttpTransport();
958 
959var app = builder.Build();
960 
961app.UseAuthentication();
962app.UseAuthorization();
963 
964app.MapMcp().RequireAuthorization();
965 
966Console.WriteLine($"Starting MCP server with authorization at {serverUrl}");
967Console.WriteLine($"Using Keycloak server at {authorizationServerUrl}");
968Console.WriteLine($"Protected Resource Metadata URL: {serverUrl}.well-known/oauth-protected-resource");
969Console.WriteLine("Exposed Math tools: Add, Multiply");
970Console.WriteLine("Press Ctrl+C to stop the server");
971 
972app.Run(serverUrl);
973```
974 
975For more details, see the [C# SDK documentation](https://github.com/modelcontextprotocol/csharp-sdk).
990976 
991977## Testing the MCP Server
992978 
from line 989
1003989 
1004990On connection, you will be taken to the browser, where you will be prompted to consent to Visual Studio Code having access to the `mcp:tools` scope.
1005991 
1006<Frame>
1007 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-vscode.png?fit=max&auto=format&n=sAd4SGUO-cEUqgzn&q=85&s=d5183fb7c257993aed1b2246f0bbbb27" alt="Keycloak consent form for VS Code." width="1915" height="1536" data-path="images/tutorial-authorization/keycloak-vscode.png" />
1008</Frame>
992![Keycloak consent form for VS Code.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-vscode.png?fit=max\&auto=format\&n=sAd4SGUO-cEUqgzn\&q=85\&s=d5183fb7c257993aed1b2246f0bbbb27)
1009993 
1010994After consenting, you will see the tools listed right above the server entry in `mcp.json`.
1011995 
1012<Frame>
1013 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/tools-vs-code.png?fit=max&auto=format&n=sAd4SGUO-cEUqgzn&q=85&s=f7c34d1bf115fe6934e01b4a5a91168b" alt="Tools listed in VS Code." width="496" height="160" data-path="images/tutorial-authorization/tools-vs-code.png" />
1014</Frame>
996![Tools listed in VS Code.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/tools-vs-code.png?fit=max\&auto=format\&n=sAd4SGUO-cEUqgzn\&q=85\&s=f7c34d1bf115fe6934e01b4a5a91168b)
1015997 
1016998You will be able to invoke individual tools with the help of the `#` sign in the chat view.
1017999 
1018<Frame>
1019 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/tools-vs-code-invoke.png?fit=max&auto=format&n=sAd4SGUO-cEUqgzn&q=85&s=76cbef68e48821a3c5467bd20c7e89fe" alt="Invoking MCP tools in VS Code." width="1276" height="396" data-path="images/tutorial-authorization/tools-vs-code-invoke.png" />
1020</Frame>
1000![Invoking MCP tools in VS Code.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/tools-vs-code-invoke.png?fit=max\&auto=format\&n=sAd4SGUO-cEUqgzn\&q=85\&s=76cbef68e48821a3c5467bd20c7e89fe)
10211001 
10221002## Common Pitfalls and How to Avoid Them
10231003 
10241004 

docs/2025-06-18/tutorials/security/security_best_practices Changed · +4 / -4 lines

from line 423
423423* Link-local: `169.254.0.0/16` (including cloud metadata endpoints)
424424* Private IPv6 ranges: `fc00::/7`, `fe80::/10`
425425 
426<Note>
427 Avoid implementing IP validation manually. Attackers exploit encoding tricks
428 (octal, hex, IPv4-mapped IPv6) that custom parsers often miss.
429</Note>
426> [!NOTE]
427>
428> Avoid implementing IP validation manually. Attackers exploit encoding tricks
429> (octal, hex, IPv4-mapped IPv6) that custom parsers often miss.
430430 
431431**Validate Redirect Targets**
432432 

docs/2025-11-25/develop/build-client Changed · +2444 / -2460 lines

## System Requirements ## Setting Up Your Environment ## Setting Up Your API Key ## Creating the Client ### Basic Client Structure ### Server Connection Management ### Query Processing Logic ### Interactive Chat Interface ### Main Entry Point ## Key Components Explained ### 1. Client Initialization ### 2. Server Connection ### 3. Query Processing ### 4. Interactive Interface ### 5. Resource Management ## Common Customization Points ## Running the Client ## How It Works ## Best practices ## Troubleshooting ### Server Path Issues ### Response Timing ### Common Error Messages ## System Requirements ## Setting Up Your Environment ## Setting Up Your API Key ## Creating the Client ### Basic Client Structure ### Server Connection Management ### Query Processing Logic ### Interactive Chat Interface ### Main Entry Point ## Running the Client ## How It Works ## Best practices ## Troubleshooting ### Server Path Issues ### Response Timing ### Common Error Messages ## System Requirements ## Setting Up Your Environment ## How it Works ### MCP Client Configuration ### Chat Implementation ### Build and run ### Advanced Configuration ## System Requirements ## Setting up your environment ## Setting up your API key ## Creating the Client ### Basic Client Structure ### Server connection management ### Query processing logic ### Interactive chat ### Main entry point ## Running the client ## How it works ## Best practices ## Troubleshooting ### Server Path Issues ### Build Issues ### Response Timing ### Common Error Messages ## System Requirements ## Setting up your environment ## Setting up your API key ## Creating the Client ### Basic Client Structure ### Query processing logic ## Key Components Explained ### 1. Client Initialization ### 2. Server Connection ### 3. Query Processing ## Running the Client ## System Requirements ## Setting Up Your Environment ## Setting Up Your API Key ## Creating the Client ### Basic Client Structure ### Server Connection Management ### Query Processing Logic ### Interactive Chat Interface ### Main Entry Point ## Key Components Explained ### 1. Client Initialization ### 2. Server Connection ### 3. Query Processing ### 4. Interactive Interface ### 5. Resource Management ## Running the Client ## How It Works ## Best practices ## Troubleshooting ### Server Path Issues ### Response Timing ### Common Error Messages ## System Requirements ## Setting Up Your Environment ## Setting Up Your API Key ## Creating the Client ### Imports and Client Structure ### Client Initialization ### Server Connection Management ### Converting MCP Tools ### Sending Model Requests ### Query Processing Logic ### Interactive Chat Interface ### Cleanup ### Main Entry Point ### Verify the Complete File ## Running the Client ## How It Works ## Best Practices ## Troubleshooting ### Server Command Issues ### Environment File Issues ### Tool and Response Errors

The two sides of this change are more than 400 edits apart, too far apart to line up, so this is the differ's own diff of it and the words inside a line are not marked.

from line 6
66 
77Before you begin, it helps to have gone through our [Build an MCP Server](/docs/2025-11-25/develop/build-server) tutorial so you can understand how clients and servers communicate.
88 
9<Tabs>
10 <Tab title="Python">
11 [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-python)
12 
13 ## System Requirements
14 
15 Before starting, ensure your system meets these requirements:
16 
17 * Mac or Windows computer
18 * Latest Python version installed
19 * Latest version of `uv` installed
20 
21 ## Setting Up Your Environment
22 
23 First, create a new Python project with `uv`:
24 
25 <CodeGroup>
26 ```bash macOS/Linux theme={null}
27 # Create project directory
28 uv init mcp-client
29 cd mcp-client
30 
31 # Create virtual environment
32 uv venv
33 
34 # Activate virtual environment
35 source .venv/bin/activate
36 
37 # Install required packages
38 uv add mcp anthropic python-dotenv
39 
40 # Remove boilerplate files
41 rm main.py
42 
43 # Create our main file
44 touch client.py
45 ```
46 
47 ```powershell Windows theme={null}
48 # Create project directory
49 uv init mcp-client
50 cd mcp-client
51 
52 # Create virtual environment
53 uv venv
54 
55 # Activate virtual environment
56 .venv\Scripts\activate
57 
58 # Install required packages
59 uv add mcp anthropic python-dotenv
60 
61 # Remove boilerplate files
62 del main.py
63 
64 # Create our main file
65 new-item client.py
66 ```
67 </CodeGroup>
68 
69 ## Setting Up Your API Key
70 
71 You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
72 
73 Create a `.env` file to store it:
74 
75 ```bash theme={null}
76 echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env
77 ```
78 
79 Add `.env` to your `.gitignore`:
80 
81 ```bash theme={null}
82 echo ".env" >> .gitignore
83 ```
84 
85 <Warning>
86 Make sure you keep your `ANTHROPIC_API_KEY` secure!
87 </Warning>
88 
89 ## Creating the Client
90 
91 ### Basic Client Structure
92 
93 First, let's set up our imports and create the basic client class:
94 
95 ```python theme={null}
96 import asyncio
97 from typing import Optional
98 from contextlib import AsyncExitStack
99 
100 from mcp import ClientSession, StdioServerParameters
101 from mcp.client.stdio import stdio_client
102 
103 from anthropic import Anthropic
104 from dotenv import load_dotenv
105 
106 load_dotenv() # load environment variables from .env
107 
108 class MCPClient:
109 def __init__(self):
110 # Initialize session and client objects
111 self.session: Optional[ClientSession] = None
112 self.exit_stack = AsyncExitStack()
113 self.anthropic = Anthropic()
114 # methods will go here
115 ```
116 
117 ### Server Connection Management
118 
119 Next, we'll implement the method to connect to an MCP server:
120 
121 ```python theme={null}
122 async def connect_to_server(self, server_script_path: str):
123 """Connect to an MCP server
124 
125 Args:
126 server_script_path: Path to the server script (.py or .js)
127 """
128 is_python = server_script_path.endswith('.py')
129 is_js = server_script_path.endswith('.js')
130 if not (is_python or is_js):
131 raise ValueError("Server script must be a .py or .js file")
132 
133 command = "python" if is_python else "node"
134 server_params = StdioServerParameters(
135 command=command,
136 args=[server_script_path],
137 env=None
138 )
139 
140 stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
141 self.stdio, self.write = stdio_transport
142 self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))
143 
144 await self.session.initialize()
145 
146 # List available tools
147 response = await self.session.list_tools()
148 tools = response.tools
149 print("\nConnected to server with tools:", [tool.name for tool in tools])
150 ```
151 
152 ### Query Processing Logic
153 
154 Now let's add the core functionality for processing queries and handling tool calls:
155 
156 ```python theme={null}
157 async def process_query(self, query: str) -> str:
158 """Process a query using Claude and available tools"""
159 messages = [
160 {
9**Python**
10 
11[You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-python)
12 
13## System Requirements
14 
15Before starting, ensure your system meets these requirements:
16 
17* Mac or Windows computer
18* Latest Python version installed
19* Latest version of `uv` installed
20 
21## Setting Up Your Environment
22 
23First, create a new Python project with `uv`:
24 
25```bash macOS/Linux theme={null}
26# Create project directory
27uv init mcp-client
28cd mcp-client
29 
30# Create virtual environment
31uv venv
32 
33# Activate virtual environment
34source .venv/bin/activate
35 
36# Install required packages
37uv add mcp anthropic python-dotenv
38 
39# Remove boilerplate files
40rm main.py
41 
42# Create our main file
43touch client.py
44```
45 
46```powershell Windows theme={null}
47# Create project directory
48uv init mcp-client
49cd mcp-client
50 
51# Create virtual environment
52uv venv
53 
54# Activate virtual environment
55.venv\Scripts\activate
56 
57# Install required packages
58uv add mcp anthropic python-dotenv
59 
60# Remove boilerplate files
61del main.py
62 
63# Create our main file
64new-item client.py
65```
66 
67## Setting Up Your API Key
68 
69You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
70 
71Create a `.env` file to store it:
72 
73```bash theme={null}
74echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env
75```
76 
77Add `.env` to your `.gitignore`:
78 
79```bash theme={null}
80echo ".env" >> .gitignore
81```
82 
83> [!WARNING]
84>
85> Make sure you keep your `ANTHROPIC_API_KEY` secure!
86 
87## Creating the Client
88 
89### Basic Client Structure
90 
91First, let's set up our imports and create the basic client class:
92 
93```python theme={null}
94import asyncio
95from typing import Optional
96from contextlib import AsyncExitStack
97 
98from mcp import ClientSession, StdioServerParameters
99from mcp.client.stdio import stdio_client
100 
101from anthropic import Anthropic
102from dotenv import load_dotenv
103 
104load_dotenv() # load environment variables from .env
105 
106class MCPClient:
107 def __init__(self):
108 # Initialize session and client objects
109 self.session: Optional[ClientSession] = None
110 self.exit_stack = AsyncExitStack()
111 self.anthropic = Anthropic()
112 # methods will go here
113```
114 
115### Server Connection Management
116 
117Next, we'll implement the method to connect to an MCP server:
118 
119```python theme={null}
120async def connect_to_server(self, server_script_path: str):
121 """Connect to an MCP server
122 
123 Args:
124 server_script_path: Path to the server script (.py or .js)
125 """
126 is_python = server_script_path.endswith('.py')
127 is_js = server_script_path.endswith('.js')
128 if not (is_python or is_js):
129 raise ValueError("Server script must be a .py or .js file")
130 
131 command = "python" if is_python else "node"
132 server_params = StdioServerParameters(
133 command=command,
134 args=[server_script_path],
135 env=None
136 )
137 
138 stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
139 self.stdio, self.write = stdio_transport
140 self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))
141 
142 await self.session.initialize()
143 
144 # List available tools
145 response = await self.session.list_tools()
146 tools = response.tools
147 print("\nConnected to server with tools:", [tool.name for tool in tools])
148```
149 
150### Query Processing Logic
151 
152Now let's add the core functionality for processing queries and handling tool calls:
153 
154```python theme={null}
155async def process_query(self, query: str) -> str:
156 """Process a query using Claude and available tools"""
157 messages = [
158 {
159 "role": "user",
160 "content": query
161 }
162 ]
163 
164 response = await self.session.list_tools()
165 available_tools = [{
166 "name": tool.name,
167 "description": tool.description,
168 "input_schema": tool.inputSchema
169 } for tool in response.tools]
170 
171 # Initial Claude API call
172 response = self.anthropic.messages.create(
173 model="claude-sonnet-4-20250514",
174 max_tokens=1000,
175 messages=messages,
176 tools=available_tools
177 )
178 
179 # Process response and handle tool calls
180 final_text = []
181 
182 assistant_message_content = []
183 for content in response.content:
184 if content.type == 'text':
185 final_text.append(content.text)
186 assistant_message_content.append(content)
187 elif content.type == 'tool_use':
188 tool_name = content.name
189 tool_args = content.input
190 
191 # Execute tool call
192 result = await self.session.call_tool(tool_name, tool_args)
193 final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")
194 
195 assistant_message_content.append(content)
196 messages.append({
197 "role": "assistant",
198 "content": assistant_message_content
199 })
200 messages.append({
161201 "role": "user",
162 "content": query
163 }
164 ]
165 
166 response = await self.session.list_tools()
167 available_tools = [{
168 "name": tool.name,
169 "description": tool.description,
170 "input_schema": tool.inputSchema
171 } for tool in response.tools]
172 
173 # Initial Claude API call
174 response = self.anthropic.messages.create(
175 model="claude-sonnet-4-20250514",
176 max_tokens=1000,
177 messages=messages,
178 tools=available_tools
179 )
180 
181 # Process response and handle tool calls
182 final_text = []
183 
184 assistant_message_content = []
185 for content in response.content:
186 if content.type == 'text':
187 final_text.append(content.text)
188 assistant_message_content.append(content)
189 elif content.type == 'tool_use':
190 tool_name = content.name
191 tool_args = content.input
192 
193 # Execute tool call
194 result = await self.session.call_tool(tool_name, tool_args)
195 final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")
196 
197 assistant_message_content.append(content)
198 messages.append({
199 "role": "assistant",
200 "content": assistant_message_content
201 })
202 messages.append({
203 "role": "user",
204 "content": [
205 {
206 "type": "tool_result",
207 "tool_use_id": content.id,
208 "content": result.content
209 }
210 ]
211 })
212 
213 # Get next response from Claude
214 response = self.anthropic.messages.create(
215 model="claude-sonnet-4-20250514",
216 max_tokens=1000,
217 messages=messages,
218 tools=available_tools
219 )
220 
221 final_text.append(response.content[0].text)
222 
223 return "\n".join(final_text)
224 ```
225 
226 ### Interactive Chat Interface
227 
228 Now we'll add the chat loop and cleanup functionality:
229 
230 ```python theme={null}
231 async def chat_loop(self):
232 """Run an interactive chat loop"""
233 print("\nMCP Client Started!")
234 print("Type your queries or 'quit' to exit.")
235 
236 while True:
237 try:
238 query = input("\nQuery: ").strip()
239 
240 if query.lower() == 'quit':
241 break
242 
243 response = await self.process_query(query)
244 print("\n" + response)
245 
246 except Exception as e:
247 print(f"\nError: {str(e)}")
248 
249 async def cleanup(self):
250 """Clean up resources"""
251 await self.exit_stack.aclose()
252 ```
253 
254 ### Main Entry Point
255 
256 Finally, we'll add the main execution logic:
257 
258 ```python theme={null}
259 async def main():
260 if len(sys.argv) < 2:
261 print("Usage: python client.py <path_to_server_script>")
262 sys.exit(1)
263 
264 client = MCPClient()
202 "content": [
203 {
204 "type": "tool_result",
205 "tool_use_id": content.id,
206 "content": result.content
207 }
208 ]
209 })
210 
211 # Get next response from Claude
212 response = self.anthropic.messages.create(
213 model="claude-sonnet-4-20250514",
214 max_tokens=1000,
215 messages=messages,
216 tools=available_tools
217 )
218 
219 final_text.append(response.content[0].text)
220 
221 return "\n".join(final_text)
222```
223 
224### Interactive Chat Interface
225 
226Now we'll add the chat loop and cleanup functionality:
227 
228```python theme={null}
229async def chat_loop(self):
230 """Run an interactive chat loop"""
231 print("\nMCP Client Started!")
232 print("Type your queries or 'quit' to exit.")
233 
234 while True:
265235 try:
266 await client.connect_to_server(sys.argv[1])
267 await client.chat_loop()
268 finally:
269 await client.cleanup()
270 
271 if __name__ == "__main__":
272 import sys
273 asyncio.run(main())
274 ```
275 
276 You can find the complete `client.py` file [here](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-python/client.py).
277 
278 ## Key Components Explained
279 
280 ### 1. Client Initialization
281 
282 * The `MCPClient` class initializes with session management and API clients
283 * Uses `AsyncExitStack` for proper resource management
284 * Configures the Anthropic client for Claude interactions
285 
286 ### 2. Server Connection
287 
288 * Supports both Python and Node.js servers
289 * Validates server script type
290 * Sets up proper communication channels
291 * Initializes the session and lists available tools
292 
293 ### 3. Query Processing
294 
295 * Maintains conversation context
296 * Handles Claude's responses and tool calls
297 * Manages the message flow between Claude and tools
298 * Combines results into a coherent response
299 
300 ### 4. Interactive Interface
301 
302 * Provides a simple command-line interface
303 * Handles user input and displays responses
304 * Includes basic error handling
305 * Allows graceful exit
306 
307 ### 5. Resource Management
308 
309 * Proper cleanup of resources
310 * Error handling for connection issues
311 * Graceful shutdown procedures
312 
313 ## Common Customization Points
314 
315 1. **Tool Handling**
316 * Modify `process_query()` to handle specific tool types
317 * Add custom error handling for tool calls
318 * Implement tool-specific response formatting
319 
320 2. **Response Processing**
321 * Customize how tool results are formatted
322 * Add response filtering or transformation
323 * Implement custom logging
324 
325 3. **User Interface**
326 * Add a GUI or web interface
327 * Implement rich console output
328 * Add command history or auto-completion
329 
330 ## Running the Client
331 
332 To run your client with any MCP server:
333 
334 ```bash theme={null}
335 uv run client.py path/to/server.py # python server
336 uv run client.py path/to/build/index.js # node server
337 ```
338 
339 <Note>
340 If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python), your command might look something like this: `python client.py .../quickstart-resources/weather-server-python/weather.py`
341 </Note>
342 
343 The client will:
344 
345 1. Connect to the specified server
346 2. List available tools
347 3. Start an interactive chat session where you can:
348 * Enter queries
349 * See tool executions
350 * Get responses from Claude
351 
352 Here's an example of what it should look like if connected to the weather server from the server quickstart:
353 
354 <Frame>
355 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/client-claude-cli-python.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=686d6e0ae7c54f807827db111eaed7d4" width="1932" height="1739" data-path="images/client-claude-cli-python.png" />
356 </Frame>
357 
358 ## How It Works
359 
360 When you submit a query:
361 
362 1. The client gets the list of available tools from the server
363 2. Your query is sent to Claude along with tool descriptions
364 3. Claude decides which tools (if any) to use
365 4. The client executes any requested tool calls through the server
366 5. Results are sent back to Claude
367 6. Claude provides a natural language response
368 7. The response is displayed to you
369 
370 ## Best practices
371 
372 1. **Error Handling**
373 * Always wrap tool calls in try-catch blocks
374 * Provide meaningful error messages
375 * Gracefully handle connection issues
376 
377 2. **Resource Management**
378 * Use `AsyncExitStack` for proper cleanup
379 * Close connections when done
380 * Handle server disconnections
381 
382 3. **Security**
383 * Store API keys securely in `.env`
384 * Validate server responses
385 * Be cautious with tool permissions
386 
387 4. **Tool Names**
388 * Tool names can be validated according to the format specified [here](/specification/2025-11-25/server/tools#tool-names)
389 * If a tool name conforms to the specified format, it should not fail validation by an MCP client
390 
391 ## Troubleshooting
392 
393 ### Server Path Issues
394 
395 * Double-check the path to your server script is correct
396 * Use the absolute path if the relative path isn't working
397 * For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
398 * Verify the server file has the correct extension (.py for Python or .js for Node.js)
399 
400 Example of correct path usage:
401 
402 ```bash theme={null}
403 # Relative path
404 uv run client.py ./server/weather.py
405 
406 # Absolute path
407 uv run client.py /Users/username/projects/mcp-server/weather.py
408 
409 # Windows path (either format works)
410 uv run client.py C:/projects/mcp-server/weather.py
411 uv run client.py C:\\projects\\mcp-server\\weather.py
412 ```
413 
414 ### Response Timing
415 
416 * The first response might take up to 30 seconds to return
417 * This is normal and happens while:
418 * The server initializes
419 * Claude processes the query
420 * Tools are being executed
421 * Subsequent responses are typically faster
422 * Don't interrupt the process during this initial waiting period
423 
424 ### Common Error Messages
425 
426 If you see:
427 
428 * `FileNotFoundError`: Check your server path
429 * `Connection refused`: Ensure the server is running and the path is correct
430 * `Tool execution failed`: Verify the tool's required environment variables are set
431 * `Timeout error`: Consider increasing the timeout in your client configuration
432 </Tab>
433 
434 <Tab title="TypeScript">
435 [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-typescript)
436 
437 ## System Requirements
438 
439 Before starting, ensure your system meets these requirements:
440 
441 * Mac or Windows computer
442 * Node.js 17 or higher installed
443 * Latest version of `npm` installed
444 * Anthropic API key (Claude)
445 
446 ## Setting Up Your Environment
447 
448 First, let's create and set up our project:
449 
450 <CodeGroup>
451 ```bash macOS/Linux theme={null}
452 # Create project directory
453 mkdir mcp-client-typescript
454 cd mcp-client-typescript
455 
456 # Initialize npm project
457 npm init -y
458 
459 # Install dependencies
460 npm install @anthropic-ai/sdk @modelcontextprotocol/sdk dotenv
461 
462 # Install dev dependencies
463 npm install -D @types/node typescript
464 
465 # Create source file
466 touch index.ts
467 ```
468 
469 ```powershell Windows theme={null}
470 # Create project directory
471 md mcp-client-typescript
472 cd mcp-client-typescript
473 
474 # Initialize npm project
475 npm init -y
476 
477 # Install dependencies
478 npm install @anthropic-ai/sdk @modelcontextprotocol/sdk dotenv
479 
480 # Install dev dependencies
481 npm install -D @types/node typescript
482 
483 # Create source file
484 new-item index.ts
485 ```
486 </CodeGroup>
487 
488 Update your `package.json` to set `type: "module"` and a build script:
489 
490 ```json package.json theme={null}
236 query = input("\nQuery: ").strip()
237 
238 if query.lower() == 'quit':
239 break
240 
241 response = await self.process_query(query)
242 print("\n" + response)
243 
244 except Exception as e:
245 print(f"\nError: {str(e)}")
246 
247async def cleanup(self):
248 """Clean up resources"""
249 await self.exit_stack.aclose()
250```
251 
252### Main Entry Point
253 
254Finally, we'll add the main execution logic:
255 
256```python theme={null}
257async def main():
258 if len(sys.argv) < 2:
259 print("Usage: python client.py <path_to_server_script>")
260 sys.exit(1)
261 
262 client = MCPClient()
263 try:
264 await client.connect_to_server(sys.argv[1])
265 await client.chat_loop()
266 finally:
267 await client.cleanup()
268 
269if __name__ == "__main__":
270 import sys
271 asyncio.run(main())
272```
273 
274You can find the complete `client.py` file [here](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-python/client.py).
275 
276## Key Components Explained
277 
278### 1. Client Initialization
279 
280* The `MCPClient` class initializes with session management and API clients
281* Uses `AsyncExitStack` for proper resource management
282* Configures the Anthropic client for Claude interactions
283 
284### 2. Server Connection
285 
286* Supports both Python and Node.js servers
287* Validates server script type
288* Sets up proper communication channels
289* Initializes the session and lists available tools
290 
291### 3. Query Processing
292 
293* Maintains conversation context
294* Handles Claude's responses and tool calls
295* Manages the message flow between Claude and tools
296* Combines results into a coherent response
297 
298### 4. Interactive Interface
299 
300* Provides a simple command-line interface
301* Handles user input and displays responses
302* Includes basic error handling
303* Allows graceful exit
304 
305### 5. Resource Management
306 
307* Proper cleanup of resources
308* Error handling for connection issues
309* Graceful shutdown procedures
310 
311## Common Customization Points
312 
3131. **Tool Handling**
314 * Modify `process_query()` to handle specific tool types
315 * Add custom error handling for tool calls
316 * Implement tool-specific response formatting
317 
3182. **Response Processing**
319 * Customize how tool results are formatted
320 * Add response filtering or transformation
321 * Implement custom logging
322 
3233. **User Interface**
324 * Add a GUI or web interface
325 * Implement rich console output
326 * Add command history or auto-completion
327 
328## Running the Client
329 
330To run your client with any MCP server:
331 
332```bash theme={null}
333uv run client.py path/to/server.py # python server
334uv run client.py path/to/build/index.js # node server
335```
336 
337> [!NOTE]
338>
339> If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python), your command might look something like this: `python client.py .../quickstart-resources/weather-server-python/weather.py`
340 
341The client will:
342 
3431. Connect to the specified server
3442. List available tools
3453. Start an interactive chat session where you can:
346 * Enter queries
347 * See tool executions
348 * Get responses from Claude
349 
350Here's an example of what it should look like if connected to the weather server from the server quickstart:
351 
352![](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/client-claude-cli-python.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=686d6e0ae7c54f807827db111eaed7d4)
353 
354## How It Works
355 
356When you submit a query:
357 
3581. The client gets the list of available tools from the server
3592. Your query is sent to Claude along with tool descriptions
3603. Claude decides which tools (if any) to use
3614. The client executes any requested tool calls through the server
3625. Results are sent back to Claude
3636. Claude provides a natural language response
3647. The response is displayed to you
365 
366## Best practices
367 
3681. **Error Handling**
369 * Always wrap tool calls in try-catch blocks
370 * Provide meaningful error messages
371 * Gracefully handle connection issues
372 
3732. **Resource Management**
374 * Use `AsyncExitStack` for proper cleanup
375 * Close connections when done
376 * Handle server disconnections
377 
3783. **Security**
379 * Store API keys securely in `.env`
380 * Validate server responses
381 * Be cautious with tool permissions
382 
3834. **Tool Names**
384 * Tool names can be validated according to the format specified [here](/specification/2025-11-25/server/tools#tool-names)
385 * If a tool name conforms to the specified format, it should not fail validation by an MCP client
386 
387## Troubleshooting
388 
389### Server Path Issues
390 
391* Double-check the path to your server script is correct
392* Use the absolute path if the relative path isn't working
393* For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
394* Verify the server file has the correct extension (.py for Python or .js for Node.js)
395 
396Example of correct path usage:
397 
398```bash theme={null}
399# Relative path
400uv run client.py ./server/weather.py
401 
402# Absolute path
403uv run client.py /Users/username/projects/mcp-server/weather.py
404 
405# Windows path (either format works)
406uv run client.py C:/projects/mcp-server/weather.py
407uv run client.py C:\\projects\\mcp-server\\weather.py
408```
409 
410### Response Timing
411 
412* The first response might take up to 30 seconds to return
413* This is normal and happens while:
414 * The server initializes
415 * Claude processes the query
416 * Tools are being executed
417* Subsequent responses are typically faster
418* Don't interrupt the process during this initial waiting period
419 
420### Common Error Messages
421 
422If you see:
423 
424* `FileNotFoundError`: Check your server path
425* `Connection refused`: Ensure the server is running and the path is correct
426* `Tool execution failed`: Verify the tool's required environment variables are set
427* `Timeout error`: Consider increasing the timeout in your client configuration
428 
429**TypeScript**
430 
431[You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-typescript)
432 
433## System Requirements
434 
435Before starting, ensure your system meets these requirements:
436 
437* Mac or Windows computer
438* Node.js 17 or higher installed
439* Latest version of `npm` installed
440* Anthropic API key (Claude)
441 
442## Setting Up Your Environment
443 
444First, let's create and set up our project:
445 
446```bash macOS/Linux theme={null}
447# Create project directory
448mkdir mcp-client-typescript
449cd mcp-client-typescript
450 
451# Initialize npm project
452npm init -y
453 
454# Install dependencies
455npm install @anthropic-ai/sdk @modelcontextprotocol/sdk dotenv
456 
457# Install dev dependencies
458npm install -D @types/node typescript
459 
460# Create source file
461touch index.ts
462```
463 
464```powershell Windows theme={null}
465# Create project directory
466md mcp-client-typescript
467cd mcp-client-typescript
468 
469# Initialize npm project
470npm init -y
471 
472# Install dependencies
473npm install @anthropic-ai/sdk @modelcontextprotocol/sdk dotenv
474 
475# Install dev dependencies
476npm install -D @types/node typescript
477 
478# Create source file
479new-item index.ts
480```
481 
482Update your `package.json` to set `type: "module"` and a build script:
483 
484```json package.json theme={null}
485{
486 "type": "module",
487 "scripts": {
488 "build": "tsc && chmod 755 build/index.js"
489 }
490}
491```
492 
493Create a `tsconfig.json` in the root of your project:
494 
495```json tsconfig.json theme={null}
496{
497 "compilerOptions": {
498 "target": "ES2022",
499 "module": "Node16",
500 "moduleResolution": "Node16",
501 "outDir": "./build",
502 "rootDir": "./",
503 "strict": true,
504 "esModuleInterop": true,
505 "skipLibCheck": true,
506 "forceConsistentCasingInFileNames": true
507 },
508 "include": ["index.ts"],
509 "exclude": ["node_modules"]
510}
511```
512 
513## Setting Up Your API Key
514 
515You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
516 
517Create a `.env` file to store it:
518 
519```bash theme={null}
520echo "ANTHROPIC_API_KEY=<your key here>" > .env
521```
522 
523Add `.env` to your `.gitignore`:
524 
525```bash theme={null}
526echo ".env" >> .gitignore
527```
528 
529> [!WARNING]
530>
531> Make sure you keep your `ANTHROPIC_API_KEY` secure!
532 
533## Creating the Client
534 
535### Basic Client Structure
536 
537First, let's set up our imports and create the basic client class in `index.ts`:
538 
539```typescript theme={null}
540import { Anthropic } from "@anthropic-ai/sdk";
541import {
542 MessageParam,
543 Tool,
544} from "@anthropic-ai/sdk/resources/messages/messages.mjs";
545import { Client } from "@modelcontextprotocol/sdk/client/index.js";
546import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
547import readline from "readline/promises";
548import dotenv from "dotenv";
549 
550dotenv.config();
551 
552const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
553if (!ANTHROPIC_API_KEY) {
554 throw new Error("ANTHROPIC_API_KEY is not set");
555}
556 
557class MCPClient {
558 private mcp: Client;
559 private anthropic: Anthropic;
560 private transport: StdioClientTransport | null = null;
561 private tools: Tool[] = [];
562 
563 constructor() {
564 this.anthropic = new Anthropic({
565 apiKey: ANTHROPIC_API_KEY,
566 });
567 this.mcp = new Client({ name: "mcp-client-cli", version: "1.0.0" });
568 }
569 // methods will go here
570}
571```
572 
573### Server Connection Management
574 
575Next, we'll implement the method to connect to an MCP server:
576 
577```typescript theme={null}
578async connectToServer(serverScriptPath: string) {
579 try {
580 const isJs = serverScriptPath.endsWith(".js");
581 const isPy = serverScriptPath.endsWith(".py");
582 if (!isJs && !isPy) {
583 throw new Error("Server script must be a .js or .py file");
584 }
585 const command = isPy
586 ? process.platform === "win32"
587 ? "python"
588 : "python3"
589 : process.execPath;
590 
591 this.transport = new StdioClientTransport({
592 command,
593 args: [serverScriptPath],
594 });
595 await this.mcp.connect(this.transport);
596 
597 const toolsResult = await this.mcp.listTools();
598 this.tools = toolsResult.tools.map((tool) => {
599 return {
600 name: tool.name,
601 description: tool.description,
602 input_schema: tool.inputSchema,
603 };
604 });
605 console.log(
606 "Connected to server with tools:",
607 this.tools.map(({ name }) => name)
608 );
609 } catch (e) {
610 console.log("Failed to connect to MCP server: ", e);
611 throw e;
612 }
613}
614```
615 
616### Query Processing Logic
617 
618Now let's add the core functionality for processing queries and handling tool calls:
619 
620```typescript theme={null}
621async processQuery(query: string) {
622 const messages: MessageParam[] = [
491623 {
492 "type": "module",
493 "scripts": {
494 "build": "tsc && chmod 755 build/index.js"
495 }
496 }
497 ```
498 
499 Create a `tsconfig.json` in the root of your project:
500 
501 ```json tsconfig.json theme={null}
502 {
503 "compilerOptions": {
504 "target": "ES2022",
505 "module": "Node16",
506 "moduleResolution": "Node16",
507 "outDir": "./build",
508 "rootDir": "./",
509 "strict": true,
510 "esModuleInterop": true,
511 "skipLibCheck": true,
512 "forceConsistentCasingInFileNames": true
513 },
514 "include": ["index.ts"],
515 "exclude": ["node_modules"]
516 }
517 ```
518 
519 ## Setting Up Your API Key
520 
521 You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
522 
523 Create a `.env` file to store it:
524 
525 ```bash theme={null}
526 echo "ANTHROPIC_API_KEY=<your key here>" > .env
527 ```
528 
529 Add `.env` to your `.gitignore`:
530 
531 ```bash theme={null}
532 echo ".env" >> .gitignore
533 ```
534 
535 <Warning>
536 Make sure you keep your `ANTHROPIC_API_KEY` secure!
537 </Warning>
538 
539 ## Creating the Client
540 
541 ### Basic Client Structure
542 
543 First, let's set up our imports and create the basic client class in `index.ts`:
544 
545 ```typescript theme={null}
546 import { Anthropic } from "@anthropic-ai/sdk";
547 import {
548 MessageParam,
549 Tool,
550 } from "@anthropic-ai/sdk/resources/messages/messages.mjs";
551 import { Client } from "@modelcontextprotocol/sdk/client/index.js";
552 import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
553 import readline from "readline/promises";
554 import dotenv from "dotenv";
555 
556 dotenv.config();
557 
558 const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
559 if (!ANTHROPIC_API_KEY) {
560 throw new Error("ANTHROPIC_API_KEY is not set");
561 }
562 
563 class MCPClient {
564 private mcp: Client;
565 private anthropic: Anthropic;
566 private transport: StdioClientTransport | null = null;
567 private tools: Tool[] = [];
568 
569 constructor() {
570 this.anthropic = new Anthropic({
571 apiKey: ANTHROPIC_API_KEY,
572 });
573 this.mcp = new Client({ name: "mcp-client-cli", version: "1.0.0" });
574 }
575 // methods will go here
576 }
577 ```
578 
579 ### Server Connection Management
580 
581 Next, we'll implement the method to connect to an MCP server:
582 
583 ```typescript theme={null}
584 async connectToServer(serverScriptPath: string) {
585 try {
586 const isJs = serverScriptPath.endsWith(".js");
587 const isPy = serverScriptPath.endsWith(".py");
588 if (!isJs && !isPy) {
589 throw new Error("Server script must be a .js or .py file");
590 }
591 const command = isPy
592 ? process.platform === "win32"
593 ? "python"
594 : "python3"
595 : process.execPath;
596 
597 this.transport = new StdioClientTransport({
598 command,
599 args: [serverScriptPath],
600 });
601 await this.mcp.connect(this.transport);
602 
603 const toolsResult = await this.mcp.listTools();
604 this.tools = toolsResult.tools.map((tool) => {
605 return {
606 name: tool.name,
607 description: tool.description,
608 input_schema: tool.inputSchema,
609 };
610 });
611 console.log(
612 "Connected to server with tools:",
613 this.tools.map(({ name }) => name)
614 );
615 } catch (e) {
616 console.log("Failed to connect to MCP server: ", e);
617 throw e;
618 }
619 }
620 ```
621 
622 ### Query Processing Logic
623 
624 Now let's add the core functionality for processing queries and handling tool calls:
625 
626 ```typescript theme={null}
627 async processQuery(query: string) {
628 const messages: MessageParam[] = [
629 {
630 role: "user",
631 content: query,
632 },
633 ];
624 role: "user",
625 content: query,
626 },
627 ];
628 
629 const response = await this.anthropic.messages.create({
630 model: "claude-sonnet-4-20250514",
631 max_tokens: 1000,
632 messages,
633 tools: this.tools,
634 });
635 
636 const finalText = [];
637 
638 for (const content of response.content) {
639 if (content.type === "text") {
640 finalText.push(content.text);
641 } else if (content.type === "tool_use") {
642 const toolName = content.name;
643 const toolArgs = content.input as { [x: string]: unknown } | undefined;
644 
645 const result = await this.mcp.callTool({
646 name: toolName,
647 arguments: toolArgs,
648 });
649 finalText.push(
650 `[Calling tool ${toolName} with args ${JSON.stringify(toolArgs)}]`
651 );
652 
653 messages.push({
654 role: "user",
655 content: result.content as string,
656 });
634657 
635658 const response = await this.anthropic.messages.create({
636659 model: "claude-sonnet-4-20250514",
637660 max_tokens: 1000,
638661 messages,
639 tools: this.tools,
640662 });
641663 
642 const finalText = [];
643 
644 for (const content of response.content) {
645 if (content.type === "text") {
646 finalText.push(content.text);
647 } else if (content.type === "tool_use") {
648 const toolName = content.name;
649 const toolArgs = content.input as { [x: string]: unknown } | undefined;
650 
651 const result = await this.mcp.callTool({
652 name: toolName,
653 arguments: toolArgs,
654 });
655 finalText.push(
656 `[Calling tool ${toolName} with args ${JSON.stringify(toolArgs)}]`
657 );
658 
659 messages.push({
660 role: "user",
661 content: result.content as string,
662 });
663 
664 const response = await this.anthropic.messages.create({
665 model: "claude-sonnet-4-20250514",
666 max_tokens: 1000,
667 messages,
668 });
669 
670 finalText.push(
671 response.content[0].type === "text" ? response.content[0].text : ""
672 );
673 }
664 finalText.push(
665 response.content[0].type === "text" ? response.content[0].text : ""
666 );
667 }
668 }
669 
670 return finalText.join("\n");
671}
672```
673 
674### Interactive Chat Interface
675 
676Now we'll add the chat loop and cleanup functionality:
677 
678```typescript theme={null}
679async chatLoop() {
680 const rl = readline.createInterface({
681 input: process.stdin,
682 output: process.stdout,
683 });
684 
685 try {
686 console.log("\nMCP Client Started!");
687 console.log("Type your queries or 'quit' to exit.");
688 
689 while (true) {
690 const message = await rl.question("\nQuery: ");
691 if (message.toLowerCase() === "quit") {
692 break;
674693 }
675 
676 return finalText.join("\n");
694 const response = await this.processQuery(message);
695 console.log("\n" + response);
677696 }
678 ```
679 
680 ### Interactive Chat Interface
681 
682 Now we'll add the chat loop and cleanup functionality:
683 
684 ```typescript theme={null}
685 async chatLoop() {
686 const rl = readline.createInterface({
687 input: process.stdin,
688 output: process.stdout,
689 });
690 
691 try {
692 console.log("\nMCP Client Started!");
693 console.log("Type your queries or 'quit' to exit.");
694 
695 while (true) {
696 const message = await rl.question("\nQuery: ");
697 if (message.toLowerCase() === "quit") {
698 break;
699 }
700 const response = await this.processQuery(message);
701 console.log("\n" + response);
702 }
703 } finally {
704 rl.close();
697 } finally {
698 rl.close();
699 }
700}
701 
702async cleanup() {
703 await this.mcp.close();
704}
705```
706 
707### Main Entry Point
708 
709Finally, we'll add the main execution logic:
710 
711```typescript theme={null}
712async function main() {
713 if (process.argv.length < 3) {
714 console.log("Usage: node index.ts <path_to_server_script>");
715 return;
716 }
717 const mcpClient = new MCPClient();
718 try {
719 await mcpClient.connectToServer(process.argv[2]);
720 await mcpClient.chatLoop();
721 } catch (e) {
722 console.error("Error:", e);
723 await mcpClient.cleanup();
724 process.exit(1);
725 } finally {
726 await mcpClient.cleanup();
727 process.exit(0);
728 }
729}
730 
731main();
732```
733 
734## Running the Client
735 
736To run your client with any MCP server:
737 
738```bash theme={null}
739# Build TypeScript
740npm run build
741 
742# Run the client
743node build/index.js path/to/server.py # python server
744node build/index.js path/to/build/index.js # node server
745```
746 
747> [!NOTE]
748>
749> If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript), your command might look something like this: `node build/index.js .../quickstart-resources/weather-server-typescript/build/index.js`
750 
751**The client will:**
752 
7531. Connect to the specified server
7542. List available tools
7553. Start an interactive chat session where you can:
756 * Enter queries
757 * See tool executions
758 * Get responses from Claude
759 
760## How It Works
761 
762When you submit a query:
763 
7641. The client gets the list of available tools from the server
7652. Your query is sent to Claude along with tool descriptions
7663. Claude decides which tools (if any) to use
7674. The client executes any requested tool calls through the server
7685. Results are sent back to Claude
7696. Claude provides a natural language response
7707. The response is displayed to you
771 
772## Best practices
773 
7741. **Error Handling**
775 * Use TypeScript's type system for better error detection
776 * Wrap tool calls in try-catch blocks
777 * Provide meaningful error messages
778 * Gracefully handle connection issues
779 
7802. **Security**
781 * Store API keys securely in `.env`
782 * Validate server responses
783 * Be cautious with tool permissions
784 
785## Troubleshooting
786 
787### Server Path Issues
788 
789* Double-check the path to your server script is correct
790* Use the absolute path if the relative path isn't working
791* For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
792* Verify the server file has the correct extension (.js for Node.js or .py for Python)
793 
794Example of correct path usage:
795 
796```bash theme={null}
797# Relative path
798node build/index.js ./server/build/index.js
799 
800# Absolute path
801node build/index.js /Users/username/projects/mcp-server/build/index.js
802 
803# Windows path (either format works)
804node build/index.js C:/projects/mcp-server/build/index.js
805node build/index.js C:\\projects\\mcp-server\\build\\index.js
806```
807 
808### Response Timing
809 
810* The first response might take up to 30 seconds to return
811* This is normal and happens while:
812 * The server initializes
813 * Claude processes the query
814 * Tools are being executed
815* Subsequent responses are typically faster
816* Don't interrupt the process during this initial waiting period
817 
818### Common Error Messages
819 
820If you see:
821 
822* `Error: Cannot find module`: Check your build folder and ensure TypeScript compilation succeeded
823* `Connection refused`: Ensure the server is running and the path is correct
824* `Tool execution failed`: Verify the tool's required environment variables are set
825* `ANTHROPIC_API_KEY is not set`: Check your .env file and environment variables
826* `TypeError`: Ensure you're using the correct types for tool arguments
827* `BadRequestError`: Ensure you have enough credits to access the Anthropic API
828 
829**Java**
830 
831> [!NOTE]
832>
833> This is a quickstart demo based on Spring AI MCP auto-configuration and boot starters.
834> To learn how to create sync and async MCP Clients manually, consult the [Java SDK Client](https://java.sdk.modelcontextprotocol.io/) documentation
835 
836This example demonstrates how to build an interactive chatbot that combines Spring AI's Model Context Protocol (MCP) with the [Brave Search MCP Server](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/brave-search). The application creates a conversational interface powered by Anthropic's Claude AI model that can perform internet searches through Brave Search, enabling natural language interactions with real-time web data.
837[You can find the complete code for this tutorial here.](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/web-search/brave-chatbot)
838 
839## System Requirements
840 
841Before starting, ensure your system meets these requirements:
842 
843* Java 17 or higher
844* Maven 3.6+
845* npx package manager
846* Anthropic API key (Claude)
847* Brave Search API key
848 
849## Setting Up Your Environment
850 
8511. Install npx (Node Package eXecute):
852 First, make sure to install [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)
853 and then run:
854 
855 ```bash theme={null}
856 npm install -g npx
857 ```
858 
8592. Clone the repository:
860 
861 ```bash theme={null}
862 git clone https://github.com/spring-projects/spring-ai-examples.git
863 cd model-context-protocol/web-search/brave-chatbot
864 ```
865 
8663. Set up your API keys:
867 
868 ```bash theme={null}
869 export ANTHROPIC_API_KEY='your-anthropic-api-key-here'
870 export BRAVE_API_KEY='your-brave-api-key-here'
871 ```
872 
8734. Build the application:
874 
875 ```bash theme={null}
876 ./mvnw clean install
877 ```
878 
8795. Run the application using Maven:
880 ```bash theme={null}
881 ./mvnw spring-boot:run
882 ```
883 
884> [!WARNING]
885>
886> Make sure you keep your `ANTHROPIC_API_KEY` and `BRAVE_API_KEY` keys secure!
887 
888## How it Works
889 
890The application integrates Spring AI with the Brave Search MCP server through several components:
891 
892### MCP Client Configuration
893 
8941. Required dependencies in pom.xml:
895 
896```xml theme={null}
897<dependency>
898 <groupId>org.springframework.ai</groupId>
899 <artifactId>spring-ai-starter-mcp-client</artifactId>
900</dependency>
901<dependency>
902 <groupId>org.springframework.ai</groupId>
903 <artifactId>spring-ai-starter-model-anthropic</artifactId>
904</dependency>
905```
906 
9072. Application properties (application.yml):
908 
909```yml theme={null}
910spring:
911 ai:
912 mcp:
913 client:
914 enabled: true
915 name: brave-search-client
916 version: 1.0.0
917 type: SYNC
918 request-timeout: 20s
919 stdio:
920 root-change-notification: true
921 servers-configuration: classpath:/mcp-servers-config.json
922 toolcallback:
923 enabled: true
924 anthropic:
925 api-key: ${ANTHROPIC_API_KEY}
926```
927 
928This activates the `spring-ai-starter-mcp-client` to create one or more `McpClient`s based on the provided server configuration.
929The `spring.ai.mcp.client.toolcallback.enabled=true` property enables the tool callback mechanism, that automatically registers all MCP tool as spring ai tools.
930It is disabled by default.
931 
9323. MCP Server Configuration (`mcp-servers-config.json`):
933 
934```json theme={null}
935{
936 "mcpServers": {
937 "brave-search": {
938 "command": "npx",
939 "args": ["-y", "@modelcontextprotocol/server-brave-search"],
940 "env": {
941 "BRAVE_API_KEY": "<PUT YOUR BRAVE API KEY>"
705942 }
706943 }
707 
708 async cleanup() {
709 await this.mcp.close();
944 }
945}
946```
947 
948### Chat Implementation
949 
950The chatbot is implemented using Spring AI's ChatClient with MCP tool integration:
951 
952```java theme={null}
953var chatClient = chatClientBuilder
954 .defaultSystem("You are useful assistant, expert in AI and Java.")
955 .defaultToolCallbacks((Object[]) mcpToolAdapter.toolCallbacks())
956 .defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory()))
957 .build();
958```
959 
960Key features:
961 
962* Uses Claude AI model for natural language understanding
963* Integrates Brave Search through MCP for real-time web search capabilities
964* Maintains conversation memory using InMemoryChatMemory
965* Runs as an interactive command-line application
966 
967### Build and run
968 
969```bash theme={null}
970./mvnw clean install
971java -jar ./target/ai-mcp-brave-chatbot-0.0.1-SNAPSHOT.jar
972```
973 
974or
975 
976```bash theme={null}
977./mvnw spring-boot:run
978```
979 
980The application will start an interactive chat session where you can ask questions. The chatbot will use Brave Search when it needs to find information from the internet to answer your queries.
981 
982The chatbot can:
983 
984* Answer questions using its built-in knowledge
985* Perform web searches when needed using Brave Search
986* Remember context from previous messages in the conversation
987* Combine information from multiple sources to provide comprehensive answers
988 
989### Advanced Configuration
990 
991The MCP client supports additional configuration options:
992 
993* Client customization through `McpSyncClientCustomizer` or `McpAsyncClientCustomizer`
994* Multiple clients with multiple transport types: `STDIO` and `SSE` (Server-Sent Events)
995* Integration with Spring AI's tool execution framework
996* Automatic client initialization and lifecycle management
997 
998For WebFlux-based applications, you can use the WebFlux starter instead:
999 
1000```xml theme={null}
1001<dependency>
1002 <groupId>org.springframework.ai</groupId>
1003 <artifactId>spring-ai-mcp-client-webflux-spring-boot-starter</artifactId>
1004</dependency>
1005```
1006 
1007This provides similar functionality but uses a WebFlux-based SSE transport implementation, recommended for production deployments.
1008 
1009**Kotlin**
1010 
1011[You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/kotlin-mcp-client)
1012 
1013## System Requirements
1014 
1015Before starting, ensure your system meets these requirements:
1016 
1017* JDK 11 or higher
1018* Anthropic API key (Claude)
1019 
1020## Setting up your environment
1021 
1022First, let's install `java` and `gradle` if you haven't already.
1023You can download `java` from [official Oracle JDK website](https://www.oracle.com/java/technologies/downloads/).
1024Verify your `java` installation:
1025 
1026```bash theme={null}
1027java --version
1028```
1029 
1030Now, let's create and set up your project:
1031 
1032```bash macOS/Linux theme={null}
1033# Create a new directory for our project
1034mkdir kotlin-mcp-client
1035cd kotlin-mcp-client
1036 
1037# Initialize a new kotlin project
1038gradle init
1039```
1040 
1041```powershell Windows theme={null}
1042# Create a new directory for our project
1043md kotlin-mcp-client
1044cd kotlin-mcp-client
1045# Initialize a new kotlin project
1046gradle init
1047```
1048 
1049After running `gradle init`, select **Application** as the project type, **Kotlin** as the programming language.
1050 
1051Alternatively, you can create a Kotlin application using the [IntelliJ IDEA project wizard](https://kotlinlang.org/docs/jvm-get-started.html).
1052 
1053After creating the project, replace the contents of your `build.gradle.kts` with:
1054 
1055```kotlin build.gradle.kts theme={null}
1056// Check latest versions at https://github.com/modelcontextprotocol/kotlin-sdk/releases
1057val mcpVersion = "0.9.0"
1058val ktorVersion = "3.2.3"
1059val anthropicVersion = "2.15.0"
1060val slf4jVersion = "2.0.17"
1061 
1062plugins {
1063 kotlin("jvm") version "2.3.20"
1064 id("com.gradleup.shadow") version "8.3.9"
1065 application
1066}
1067 
1068application {
1069 mainClass.set("MainKt")
1070}
1071 
1072dependencies {
1073 implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion")
1074 implementation("io.ktor:ktor-client-cio:$ktorVersion")
1075 implementation("com.anthropic:anthropic-java:$anthropicVersion")
1076 implementation("org.slf4j:slf4j-simple:$slf4jVersion")
1077}
1078```
1079 
1080Verify that everything is set up correctly:
1081 
1082```bash theme={null}
1083./gradlew build
1084```
1085 
1086## Setting up your API key
1087 
1088You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
1089 
1090Set up your API key:
1091 
1092```bash theme={null}
1093export ANTHROPIC_API_KEY='your-anthropic-api-key-here'
1094```
1095 
1096> [!WARNING]
1097>
1098> Make sure you keep your `ANTHROPIC_API_KEY` secure!
1099 
1100## Creating the Client
1101 
1102### Basic Client Structure
1103 
1104First, let's create the basic client class:
1105 
1106```kotlin theme={null}
1107class MCPClient(apiKey: String) : AutoCloseable {
1108 private val anthropic = AnthropicOkHttpClient.builder()
1109 .apiKey(apiKey)
1110 .build()
1111 
1112 private val mcp: Client = Client(
1113 clientInfo = Implementation(name = "mcp-client-cli", version = "1.0.0")
1114 )
1115 private var serverProcess: Process? = null
1116 private lateinit var tools: List<ToolUnion>
1117 
1118 // methods will go here
1119 
1120 override fun close() {
1121 runBlocking {
1122 mcp.close()
1123 }
1124 serverProcess?.destroy()
1125 anthropic.close()
7101126 }
711 ```
712 
713 ### Main Entry Point
714 
715 Finally, we'll add the main execution logic:
716 
717 ```typescript theme={null}
718 async function main() {
719 if (process.argv.length < 3) {
720 console.log("Usage: node index.ts <path_to_server_script>");
721 return;
722 }
723 const mcpClient = new MCPClient();
724 try {
725 await mcpClient.connectToServer(process.argv[2]);
726 await mcpClient.chatLoop();
727 } catch (e) {
728 console.error("Error:", e);
729 await mcpClient.cleanup();
730 process.exit(1);
731 } finally {
732 await mcpClient.cleanup();
733 process.exit(0);
734 }
1127}
1128```
1129 
1130### Server connection management
1131 
1132Next, we'll implement the method to connect to an MCP server:
1133 
1134```kotlin theme={null}
1135suspend fun connectToServer(serverScriptPath: String) {
1136 val command = buildList {
1137 when (serverScriptPath.substringAfterLast(".")) {
1138 "js" -> add("node")
1139 "py" -> add(if (System.getProperty("os.name").lowercase().contains("win")) "python" else "python3")
1140 "jar" -> addAll(listOf("java", "-jar"))
1141 else -> throw IllegalArgumentException("Server script must be a .js, .py or .jar file")
1142 }
1143 add(serverScriptPath)
7351144 }
7361145 
737 main();
738 ```
739 
740 ## Running the Client
741 
742 To run your client with any MCP server:
743 
744 ```bash theme={null}
745 # Build TypeScript
746 npm run build
747 
748 # Run the client
749 node build/index.js path/to/server.py # python server
750 node build/index.js path/to/build/index.js # node server
751 ```
752 
753 <Note>
754 If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript), your command might look something like this: `node build/index.js .../quickstart-resources/weather-server-typescript/build/index.js`
755 </Note>
756 
757 **The client will:**
758 
759 1. Connect to the specified server
760 2. List available tools
761 3. Start an interactive chat session where you can:
762 * Enter queries
763 * See tool executions
764 * Get responses from Claude
765 
766 ## How It Works
767 
768 When you submit a query:
769 
770 1. The client gets the list of available tools from the server
771 2. Your query is sent to Claude along with tool descriptions
772 3. Claude decides which tools (if any) to use
773 4. The client executes any requested tool calls through the server
774 5. Results are sent back to Claude
775 6. Claude provides a natural language response
776 7. The response is displayed to you
777 
778 ## Best practices
779 
780 1. **Error Handling**
781 * Use TypeScript's type system for better error detection
782 * Wrap tool calls in try-catch blocks
783 * Provide meaningful error messages
784 * Gracefully handle connection issues
785 
786 2. **Security**
787 * Store API keys securely in `.env`
788 * Validate server responses
789 * Be cautious with tool permissions
790 
791 ## Troubleshooting
792 
793 ### Server Path Issues
794 
795 * Double-check the path to your server script is correct
796 * Use the absolute path if the relative path isn't working
797 * For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
798 * Verify the server file has the correct extension (.js for Node.js or .py for Python)
799 
800 Example of correct path usage:
801 
802 ```bash theme={null}
803 # Relative path
804 node build/index.js ./server/build/index.js
805 
806 # Absolute path
807 node build/index.js /Users/username/projects/mcp-server/build/index.js
808 
809 # Windows path (either format works)
810 node build/index.js C:/projects/mcp-server/build/index.js
811 node build/index.js C:\\projects\\mcp-server\\build\\index.js
812 ```
813 
814 ### Response Timing
815 
816 * The first response might take up to 30 seconds to return
817 * This is normal and happens while:
818 * The server initializes
819 * Claude processes the query
820 * Tools are being executed
821 * Subsequent responses are typically faster
822 * Don't interrupt the process during this initial waiting period
823 
824 ### Common Error Messages
825 
826 If you see:
827 
828 * `Error: Cannot find module`: Check your build folder and ensure TypeScript compilation succeeded
829 * `Connection refused`: Ensure the server is running and the path is correct
830 * `Tool execution failed`: Verify the tool's required environment variables are set
831 * `ANTHROPIC_API_KEY is not set`: Check your .env file and environment variables
832 * `TypeError`: Ensure you're using the correct types for tool arguments
833 * `BadRequestError`: Ensure you have enough credits to access the Anthropic API
834 </Tab>
835 
836 <Tab title="Java">
837 <Note>
838 This is a quickstart demo based on Spring AI MCP auto-configuration and boot starters.
839 To learn how to create sync and async MCP Clients manually, consult the [Java SDK Client](https://java.sdk.modelcontextprotocol.io/) documentation
840 </Note>
841 
842 This example demonstrates how to build an interactive chatbot that combines Spring AI's Model Context Protocol (MCP) with the [Brave Search MCP Server](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/brave-search). The application creates a conversational interface powered by Anthropic's Claude AI model that can perform internet searches through Brave Search, enabling natural language interactions with real-time web data.
843 [You can find the complete code for this tutorial here.](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/web-search/brave-chatbot)
844 
845 ## System Requirements
846 
847 Before starting, ensure your system meets these requirements:
848 
849 * Java 17 or higher
850 * Maven 3.6+
851 * npx package manager
852 * Anthropic API key (Claude)
853 * Brave Search API key
854 
855 ## Setting Up Your Environment
856 
857 1. Install npx (Node Package eXecute):
858 First, make sure to install [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)
859 and then run:
860 
861 ```bash theme={null}
862 npm install -g npx
863 ```
864 
865 2. Clone the repository:
866 
867 ```bash theme={null}
868 git clone https://github.com/spring-projects/spring-ai-examples.git
869 cd model-context-protocol/web-search/brave-chatbot
870 ```
871 
872 3. Set up your API keys:
873 
874 ```bash theme={null}
875 export ANTHROPIC_API_KEY='your-anthropic-api-key-here'
876 export BRAVE_API_KEY='your-brave-api-key-here'
877 ```
878 
879 4. Build the application:
880 
881 ```bash theme={null}
882 ./mvnw clean install
883 ```
884 
885 5. Run the application using Maven:
886 ```bash theme={null}
887 ./mvnw spring-boot:run
888 ```
889 
890 <Warning>
891 Make sure you keep your `ANTHROPIC_API_KEY` and `BRAVE_API_KEY` keys secure!
892 </Warning>
893 
894 ## How it Works
895 
896 The application integrates Spring AI with the Brave Search MCP server through several components:
897 
898 ### MCP Client Configuration
899 
900 1. Required dependencies in pom.xml:
901 
902 ```xml theme={null}
903 <dependency>
904 <groupId>org.springframework.ai</groupId>
905 <artifactId>spring-ai-starter-mcp-client</artifactId>
906 </dependency>
907 <dependency>
908 <groupId>org.springframework.ai</groupId>
909 <artifactId>spring-ai-starter-model-anthropic</artifactId>
910 </dependency>
911 ```
912 
913 2. Application properties (application.yml):
914 
915 ```yml theme={null}
916 spring:
917 ai:
918 mcp:
919 client:
920 enabled: true
921 name: brave-search-client
922 version: 1.0.0
923 type: SYNC
924 request-timeout: 20s
925 stdio:
926 root-change-notification: true
927 servers-configuration: classpath:/mcp-servers-config.json
928 toolcallback:
929 enabled: true
930 anthropic:
931 api-key: ${ANTHROPIC_API_KEY}
932 ```
933 
934 This activates the `spring-ai-starter-mcp-client` to create one or more `McpClient`s based on the provided server configuration.
935 The `spring.ai.mcp.client.toolcallback.enabled=true` property enables the tool callback mechanism, that automatically registers all MCP tool as spring ai tools.
936 It is disabled by default.
937 
938 3. MCP Server Configuration (`mcp-servers-config.json`):
939 
940 ```json theme={null}
941 {
942 "mcpServers": {
943 "brave-search": {
944 "command": "npx",
945 "args": ["-y", "@modelcontextprotocol/server-brave-search"],
946 "env": {
947 "BRAVE_API_KEY": "<PUT YOUR BRAVE API KEY>"
948 }
949 }
950 }
951 }
952 ```
953 
954 ### Chat Implementation
955 
956 The chatbot is implemented using Spring AI's ChatClient with MCP tool integration:
957 
958 ```java theme={null}
959 var chatClient = chatClientBuilder
960 .defaultSystem("You are useful assistant, expert in AI and Java.")
961 .defaultToolCallbacks((Object[]) mcpToolAdapter.toolCallbacks())
962 .defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory()))
963 .build();
964 ```
965 
966 Key features:
967 
968 * Uses Claude AI model for natural language understanding
969 * Integrates Brave Search through MCP for real-time web search capabilities
970 * Maintains conversation memory using InMemoryChatMemory
971 * Runs as an interactive command-line application
972 
973 ### Build and run
974 
975 ```bash theme={null}
976 ./mvnw clean install
977 java -jar ./target/ai-mcp-brave-chatbot-0.0.1-SNAPSHOT.jar
978 ```
979 
980 or
981 
982 ```bash theme={null}
983 ./mvnw spring-boot:run
984 ```
985 
986 The application will start an interactive chat session where you can ask questions. The chatbot will use Brave Search when it needs to find information from the internet to answer your queries.
987 
988 The chatbot can:
989 
990 * Answer questions using its built-in knowledge
991 * Perform web searches when needed using Brave Search
992 * Remember context from previous messages in the conversation
993 * Combine information from multiple sources to provide comprehensive answers
994 
995 ### Advanced Configuration
996 
997 The MCP client supports additional configuration options:
998 
999 * Client customization through `McpSyncClientCustomizer` or `McpAsyncClientCustomizer`
1000 * Multiple clients with multiple transport types: `STDIO` and `SSE` (Server-Sent Events)
1001 * Integration with Spring AI's tool execution framework
1002 * Automatic client initialization and lifecycle management
1003 
1004 For WebFlux-based applications, you can use the WebFlux starter instead:
1005 
1006 ```xml theme={null}
1007 <dependency>
1008 <groupId>org.springframework.ai</groupId>
1009 <artifactId>spring-ai-mcp-client-webflux-spring-boot-starter</artifactId>
1010 </dependency>
1011 ```
1012 
1013 This provides similar functionality but uses a WebFlux-based SSE transport implementation, recommended for production deployments.
1014 </Tab>
1015 
1016 <Tab title="Kotlin">
1017 [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/kotlin-mcp-client)
1018 
1019 ## System Requirements
1020 
1021 Before starting, ensure your system meets these requirements:
1022 
1023 * JDK 11 or higher
1024 * Anthropic API key (Claude)
1025 
1026 ## Setting up your environment
1027 
1028 First, let's install `java` and `gradle` if you haven't already.
1029 You can download `java` from [official Oracle JDK website](https://www.oracle.com/java/technologies/downloads/).
1030 Verify your `java` installation:
1031 
1032 ```bash theme={null}
1033 java --version
1034 ```
1035 
1036 Now, let's create and set up your project:
1037 
1038 <CodeGroup>
1039 ```bash macOS/Linux theme={null}
1040 # Create a new directory for our project
1041 mkdir kotlin-mcp-client
1042 cd kotlin-mcp-client
1043 
1044 # Initialize a new kotlin project
1045 gradle init
1046 ```
1047 
1048 ```powershell Windows theme={null}
1049 # Create a new directory for our project
1050 md kotlin-mcp-client
1051 cd kotlin-mcp-client
1052 # Initialize a new kotlin project
1053 gradle init
1054 ```
1055 </CodeGroup>
1056 
1057 After running `gradle init`, select **Application** as the project type, **Kotlin** as the programming language.
1058 
1059 Alternatively, you can create a Kotlin application using the [IntelliJ IDEA project wizard](https://kotlinlang.org/docs/jvm-get-started.html).
1060 
1061 After creating the project, replace the contents of your `build.gradle.kts` with:
1062 
1063 ```kotlin build.gradle.kts theme={null}
1064 // Check latest versions at https://github.com/modelcontextprotocol/kotlin-sdk/releases
1065 val mcpVersion = "0.9.0"
1066 val ktorVersion = "3.2.3"
1067 val anthropicVersion = "2.15.0"
1068 val slf4jVersion = "2.0.17"
1069 
1070 plugins {
1071 kotlin("jvm") version "2.3.20"
1072 id("com.gradleup.shadow") version "8.3.9"
1073 application
1074 }
1075 
1076 application {
1077 mainClass.set("MainKt")
1078 }
1079 
1080 dependencies {
1081 implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion")
1082 implementation("io.ktor:ktor-client-cio:$ktorVersion")
1083 implementation("com.anthropic:anthropic-java:$anthropicVersion")
1084 implementation("org.slf4j:slf4j-simple:$slf4jVersion")
1085 }
1086 ```
1087 
1088 Verify that everything is set up correctly:
1089 
1090 ```bash theme={null}
1091 ./gradlew build
1092 ```
1093 
1094 ## Setting up your API key
1095 
1096 You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
1097 
1098 Set up your API key:
1099 
1100 ```bash theme={null}
1101 export ANTHROPIC_API_KEY='your-anthropic-api-key-here'
1102 ```
1103 
1104 <Warning>
1105 Make sure you keep your `ANTHROPIC_API_KEY` secure!
1106 </Warning>
1107 
1108 ## Creating the Client
1109 
1110 ### Basic Client Structure
1111 
1112 First, let's create the basic client class:
1113 
1114 ```kotlin theme={null}
1115 class MCPClient(apiKey: String) : AutoCloseable {
1116 private val anthropic = AnthropicOkHttpClient.builder()
1117 .apiKey(apiKey)
1118 .build()
1119 
1120 private val mcp: Client = Client(
1121 clientInfo = Implementation(name = "mcp-client-cli", version = "1.0.0")
1122 )
1123 private var serverProcess: Process? = null
1124 private lateinit var tools: List<ToolUnion>
1125 
1126 // methods will go here
1127 
1128 override fun close() {
1129 runBlocking {
1130 mcp.close()
1131 }
1132 serverProcess?.destroy()
1133 anthropic.close()
1134 }
1135 }
1136 ```
1137 
1138 ### Server connection management
1139 
1140 Next, we'll implement the method to connect to an MCP server:
1141 
1142 ```kotlin theme={null}
1143 suspend fun connectToServer(serverScriptPath: String) {
1144 val command = buildList {
1145 when (serverScriptPath.substringAfterLast(".")) {
1146 "js" -> add("node")
1147 "py" -> add(if (System.getProperty("os.name").lowercase().contains("win")) "python" else "python3")
1148 "jar" -> addAll(listOf("java", "-jar"))
1149 else -> throw IllegalArgumentException("Server script must be a .js, .py or .jar file")
1150 }
1151 add(serverScriptPath)
1152 }
1153 
1154 val process = ProcessBuilder(command).start()
1155 serverProcess = process
1156 
1157 val transport = StdioClientTransport(
1158 input = process.inputStream.asSource().buffered(),
1159 output = process.outputStream.asSink().buffered(),
1160 )
1161 
1162 mcp.connect(transport)
1163 
1164 val toolsResult = mcp.listTools()
1165 tools = toolsResult.tools.map { tool ->
1166 ToolUnion.ofTool(
1167 Tool.builder()
1168 .name(tool.name)
1169 .description(tool.description ?: "")
1170 .inputSchema(
1171 Tool.InputSchema.builder()
1172 .type(JsonValue.from(tool.inputSchema.type))
1173 .properties(tool.inputSchema.properties?.toJsonValue() ?: EmptyJsonObject.toJsonValue())
1174 .putAdditionalProperty("required", JsonValue.from(tool.inputSchema.required))
1175 .build(),
1176 )
1177 .build(),
1178 )
1179 }
1180 println("Connected to server with tools: ${tools.joinToString(", ") { it.tool().get().name() }}")
1181 }
1182 ```
1183 
1184 <Accordion title="JsonObject.toJsonValue() helper">
1185 This helper converts a kotlinx.serialization `JsonObject` to an Anthropic SDK `JsonValue` using Jackson:
1186 
1187 ```kotlin theme={null}
1188 private fun JsonObject.toJsonValue(): JsonValue {
1189 val mapper = ObjectMapper()
1190 val node = mapper.readTree(this.toString())
1191 return JsonValue.fromJsonNode(node)
1192 }
1193 ```
1194 </Accordion>
1195 
1196 ### Query processing logic
1197 
1198 Now let's add the core functionality for processing queries and handling tool calls:
1199 
1200 ```kotlin theme={null}
1201 suspend fun processQuery(query: String): String {
1202 val messages = mutableListOf(
1203 MessageParam.builder()
1204 .role(MessageParam.Role.USER)
1205 .content(query)
1146 val process = ProcessBuilder(command).start()
1147 serverProcess = process
1148 
1149 val transport = StdioClientTransport(
1150 input = process.inputStream.asSource().buffered(),
1151 output = process.outputStream.asSink().buffered(),
1152 )
1153 
1154 mcp.connect(transport)
1155 
1156 val toolsResult = mcp.listTools()
1157 tools = toolsResult.tools.map { tool ->
1158 ToolUnion.ofTool(
1159 Tool.builder()
1160 .name(tool.name)
1161 .description(tool.description ?: "")
1162 .inputSchema(
1163 Tool.InputSchema.builder()
1164 .type(JsonValue.from(tool.inputSchema.type))
1165 .properties(tool.inputSchema.properties?.toJsonValue() ?: EmptyJsonObject.toJsonValue())
1166 .putAdditionalProperty("required", JsonValue.from(tool.inputSchema.required))
1167 .build(),
1168 )
12061169 .build(),
12071170 )
1208 
1209 val response = anthropic.messages().create(
1210 MessageCreateParams.builder()
1211 .model("claude-sonnet-4-20250514")
1212 .maxTokens(1024)
1213 .messages(messages)
1214 .tools(tools)
1215 .build(),
1216 )
1217 
1218 val finalText = mutableListOf<String>()
1219 response.content().forEach { content ->
1220 when {
1221 content.isText() -> finalText.add(content.text().get().text())
1222 
1223 content.isToolUse() -> {
1224 val toolName = content.toolUse().get().name()
1225 val toolArgs =
1226 content.toolUse().get()._input().convert(object : TypeReference<Map<String, JsonValue>>() {})
1227 
1228 val result = mcp.callTool(
1229 name = toolName,
1230 arguments = toolArgs ?: emptyMap(),
1231 )
1232 finalText.add("[Calling tool $toolName with args $toolArgs]")
1233 
1234 messages.add(
1235 MessageParam.builder()
1236 .role(MessageParam.Role.USER)
1237 .content(
1238 result.content
1239 .filterIsInstance<TextContent>()
1240 .joinToString("\n") { it.text }
1241 )
1242 .build(),
1243 )
1244 
1245 val aiResponse = anthropic.messages().create(
1246 MessageCreateParams.builder()
1247 .model("claude-sonnet-4-20250514")
1248 .maxTokens(1024)
1249 .messages(messages)
1250 .build(),
1251 )
1252 
1253 finalText.add(aiResponse.content().first().text().get().text())
1254 }
1255 }
1256 }
1257 
1258 return finalText.joinToString("\n")
12591171 }
1260 ```
1261 
1262 ### Interactive chat
1263 
1264 We'll add the chat loop:
1265 
1266 ```kotlin theme={null}
1267 suspend fun chatLoop() {
1268 println("\nMCP Client Started!")
1269 println("Type your queries or 'quit' to exit.")
1270 
1271 while (true) {
1272 print("\nQuery: ")
1273 val message = readlnOrNull() ?: break
1274 if (message.trim().lowercase() == "quit") break
1275 
1276 try {
1277 val response = processQuery(message)
1278 println("\n$response")
1279 } catch (e: Exception) {
1280 println("\nError: ${e.message}")
1172 println("Connected to server with tools: ${tools.joinToString(", ") { it.tool().get().name() }}")
1173}
1174```
1175 
1176> **JsonObject.toJsonValue() helper**
1177>
1178> This helper converts a kotlinx.serialization `JsonObject` to an Anthropic SDK `JsonValue` using Jackson:
1179>
1180> ```kotlin theme={null}
1181> private fun JsonObject.toJsonValue(): JsonValue {
1182> val mapper = ObjectMapper()
1183> val node = mapper.readTree(this.toString())
1184> return JsonValue.fromJsonNode(node)
1185> }
1186> ```
1187 
1188### Query processing logic
1189 
1190Now let's add the core functionality for processing queries and handling tool calls:
1191 
1192```kotlin theme={null}
1193suspend fun processQuery(query: String): String {
1194 val messages = mutableListOf(
1195 MessageParam.builder()
1196 .role(MessageParam.Role.USER)
1197 .content(query)
1198 .build(),
1199 )
1200 
1201 val response = anthropic.messages().create(
1202 MessageCreateParams.builder()
1203 .model("claude-sonnet-4-20250514")
1204 .maxTokens(1024)
1205 .messages(messages)
1206 .tools(tools)
1207 .build(),
1208 )
1209 
1210 val finalText = mutableListOf<String>()
1211 response.content().forEach { content ->
1212 when {
1213 content.isText() -> finalText.add(content.text().get().text())
1214 
1215 content.isToolUse() -> {
1216 val toolName = content.toolUse().get().name()
1217 val toolArgs =
1218 content.toolUse().get()._input().convert(object : TypeReference<Map<String, JsonValue>>() {})
1219 
1220 val result = mcp.callTool(
1221 name = toolName,
1222 arguments = toolArgs ?: emptyMap(),
1223 )
1224 finalText.add("[Calling tool $toolName with args $toolArgs]")
1225 
1226 messages.add(
1227 MessageParam.builder()
1228 .role(MessageParam.Role.USER)
1229 .content(
1230 result.content
1231 .filterIsInstance<TextContent>()
1232 .joinToString("\n") { it.text }
1233 )
1234 .build(),
1235 )
1236 
1237 val aiResponse = anthropic.messages().create(
1238 MessageCreateParams.builder()
1239 .model("claude-sonnet-4-20250514")
1240 .maxTokens(1024)
1241 .messages(messages)
1242 .build(),
1243 )
1244 
1245 finalText.add(aiResponse.content().first().text().get().text())
12811246 }
12821247 }
12831248 }
1284 ```
1285 
1286 ### Main entry point
1287 
1288 Finally, we'll add the main execution function:
1289 
1290 ```kotlin theme={null}
1291 fun main(args: Array<String>) = runBlocking {
1292 require(args.isNotEmpty()) { "Usage: java -jar <path> <path_to_server_script>" }
1293 
1294 val apiKey = System.getenv("ANTHROPIC_API_KEY")
1295 require(!apiKey.isNullOrBlank()) { "ANTHROPIC_API_KEY environment variable is not set" }
1296 
1297 val client = MCPClient(apiKey)
1298 client.use {
1299 client.connectToServer(args.first())
1300 client.chatLoop()
1249 
1250 return finalText.joinToString("\n")
1251}
1252```
1253 
1254### Interactive chat
1255 
1256We'll add the chat loop:
1257 
1258```kotlin theme={null}
1259suspend fun chatLoop() {
1260 println("\nMCP Client Started!")
1261 println("Type your queries or 'quit' to exit.")
1262 
1263 while (true) {
1264 print("\nQuery: ")
1265 val message = readlnOrNull() ?: break
1266 if (message.trim().lowercase() == "quit") break
1267 
1268 try {
1269 val response = processQuery(message)
1270 println("\n$response")
1271 } catch (e: Exception) {
1272 println("\nError: ${e.message}")
13011273 }
13021274 }
1303 ```
1304 
1305 ## Running the client
1306 
1307 To run your client with any MCP server:
1308 
1309 ```bash theme={null}
1310 ./gradlew build
1311 
1312 # Run the client
1313 java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar path/to/server.jar # JVM server
1314 java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar path/to/server.py # Python server
1315 java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar path/to/build/index.js # Node server
1316 ```
1317 
1318 Alternatively, you can run directly with Gradle:
1319 
1320 ```bash theme={null}
1321 ./gradlew run --args="path/to/server.jar"
1322 ```
1323 
1324 <Note>
1325 If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar .../samples/weather-stdio-server/build/libs/weather-stdio-server-0.1.0-all.jar`
1326 </Note>
1327 
1328 **The client will:**
1329 
1330 1. Connect to the specified server
1331 2. List available tools
1332 3. Start an interactive chat session where you can:
1333 * Enter queries
1334 * See tool executions
1335 * Get responses from Claude
1336 
1337 ## How it works
1338 
1339 Here's a high-level workflow schema:
1340 
1341 ```mermaid theme={null}
1342 ---
1343 config:
1344 theme: neutral
1345 ---
1346 sequenceDiagram
1347 actor User
1348 participant Client
1349 participant Claude
1350 participant MCP_Server as MCP Server
1351 participant Tools
1352 
1353 User->>Client: Send query
1354 Client<<->>MCP_Server: Get available tools
1355 Client->>Claude: Send query with tool descriptions
1356 Claude-->>Client: Decide tool execution
1357 Client->>MCP_Server: Request tool execution
1358 MCP_Server->>Tools: Execute chosen tools
1359 Tools-->>MCP_Server: Return results
1360 MCP_Server-->>Client: Send results
1361 Client->>Claude: Send tool results
1362 Claude-->>Client: Provide final response
1363 Client-->>User: Display response
1364 ```
1365 
1366 When you submit a query:
1367 
1368 1. The client gets the list of available tools from the server
1369 2. Your query is sent to Claude along with tool descriptions
1370 3. Claude decides which tools (if any) to use
1371 4. The client executes any requested tool calls through the server
1372 5. Results are sent back to Claude
1373 6. Claude provides a natural language response
1374 7. The response is displayed to you
1375 
1376 ## Best practices
1377 
1378 1. **Error Handling**
1379 * Leverage Kotlin's type system to model errors explicitly
1380 * Wrap external tool and API calls in `try-catch` blocks when exceptions are possible
1381 * Provide clear and meaningful error messages
1382 * Handle network timeouts and connection issues gracefully
1383 
1384 2. **Security**
1385 * Store API keys and secrets securely in `local.properties`, environment variables, or secret managers
1386 * Validate all external responses to avoid unexpected or unsafe data usage
1387 * Be cautious with permissions and trust boundaries when using tools
1388 
1389 3. **Environment**
1390 * Set `ANTHROPIC_API_KEY` through environment variables rather than hardcoding
1391 * Use `.env` files with appropriate `.gitignore` rules for local development
1392 
1393 ## Troubleshooting
1394 
1395 ### Server Path Issues
1396 
1397 * Double-check the path to your server script is correct
1398 * Use the absolute path if the relative path isn't working
1399 * For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
1400 * Make sure that the required runtime is installed (java for Java, npm for Node.js, or uv for Python)
1401 * Verify the server file has the correct extension (.jar for Java, .js for Node.js or .py for Python)
1402 
1403 Example of correct path usage:
1404 
1405 ```bash theme={null}
1406 # Relative path
1407 java -jar build/libs/client.jar ./server/build/libs/server.jar
1408 
1409 # Absolute path
1410 java -jar build/libs/client.jar /Users/username/projects/mcp-server/build/libs/server.jar
1411 
1412 # Windows path (either format works)
1413 java -jar build/libs/client.jar C:/projects/mcp-server/build/libs/server.jar
1414 java -jar build/libs/client.jar C:\\projects\\mcp-server\\build\\libs\\server.jar
1415 ```
1416 
1417 ### Build Issues
1418 
1419 * Use `./gradlew build` or `./gradlew shadowJar` (not `./gradlew jar`) to create the shadow JAR with all dependencies
1420 * If you get JDK version errors, ensure your installed JDK version matches or exceeds the `jvmToolchain` setting in `build.gradle.kts`
1421 
1422 ### Response Timing
1423 
1424 * The first response might take up to 30 seconds to return
1425 * This is normal and happens while:
1426 * The server initializes
1427 * Claude processes the query
1428 * Tools are being executed
1429 * Subsequent responses are typically faster
1430 * Don't interrupt the process during this initial waiting period
1431 
1432 ### Common Error Messages
1433 
1434 If you see:
1435 
1436 * `Connection refused`: Ensure the server is running and the path is correct
1437 * `Tool execution failed`: Verify the tool's required environment variables are set
1438 * `ANTHROPIC_API_KEY is not set`: Check your environment variables
1439 </Tab>
1440 
1441 <Tab title="C#">
1442 [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/csharp-sdk/tree/main/samples/QuickstartClient)
1443 
1444 ## System Requirements
1445 
1446 Before starting, ensure your system meets these requirements:
1447 
1448 * .NET 8.0 or higher
1449 * Anthropic API key (Claude)
1450 * Windows, Linux, or macOS
1451 
1452 ## Setting up your environment
1453 
1454 First, create a new .NET project:
1455 
1456 ```bash theme={null}
1457 dotnet new console -n QuickstartClient
1458 cd QuickstartClient
1459 ```
1460 
1461 Then, add the required dependencies to your project:
1462 
1463 ```bash theme={null}
1464 dotnet add package ModelContextProtocol --prerelease
1465 dotnet add package Anthropic.SDK
1466 dotnet add package Microsoft.Extensions.Hosting
1467 dotnet add package Microsoft.Extensions.AI
1468 ```
1469 
1470 ## Setting up your API key
1471 
1472 You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
1473 
1474 ```bash theme={null}
1475 dotnet user-secrets init
1476 dotnet user-secrets set "ANTHROPIC_API_KEY" "<your key here>"
1477 ```
1478 
1479 ## Creating the Client
1480 
1481 ### Basic Client Structure
1482 
1483 First, let's setup the basic client class in the file `Program.cs`:
1484 
1485 ```csharp theme={null}
1486 using Anthropic.SDK;
1487 using Microsoft.Extensions.AI;
1488 using Microsoft.Extensions.Configuration;
1489 using Microsoft.Extensions.Hosting;
1490 using ModelContextProtocol.Client;
1491 using ModelContextProtocol.Protocol.Transport;
1492 
1493 var builder = Host.CreateApplicationBuilder(args);
1494 
1495 builder.Configuration
1496 .AddEnvironmentVariables()
1497 .AddUserSecrets<Program>();
1498 ```
1499 
1500 This creates the beginnings of a .NET console application that can read the API key from user secrets.
1501 
1502 Next, we'll setup the MCP Client:
1503 
1504 ```csharp theme={null}
1505 var (command, arguments) = GetCommandAndArguments(args);
1506 
1507 var clientTransport = new StdioClientTransport(new()
1275}
1276```
1277 
1278### Main entry point
1279 
1280Finally, we'll add the main execution function:
1281 
1282```kotlin theme={null}
1283fun main(args: Array<String>) = runBlocking {
1284 require(args.isNotEmpty()) { "Usage: java -jar <path> <path_to_server_script>" }
1285 
1286 val apiKey = System.getenv("ANTHROPIC_API_KEY")
1287 require(!apiKey.isNullOrBlank()) { "ANTHROPIC_API_KEY environment variable is not set" }
1288 
1289 val client = MCPClient(apiKey)
1290 client.use {
1291 client.connectToServer(args.first())
1292 client.chatLoop()
1293 }
1294}
1295```
1296 
1297## Running the client
1298 
1299To run your client with any MCP server:
1300 
1301```bash theme={null}
1302./gradlew build
1303 
1304# Run the client
1305java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar path/to/server.jar # JVM server
1306java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar path/to/server.py # Python server
1307java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar path/to/build/index.js # Node server
1308```
1309 
1310Alternatively, you can run directly with Gradle:
1311 
1312```bash theme={null}
1313./gradlew run --args="path/to/server.jar"
1314```
1315 
1316> [!NOTE]
1317>
1318> If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar .../samples/weather-stdio-server/build/libs/weather-stdio-server-0.1.0-all.jar`
1319 
1320**The client will:**
1321 
13221. Connect to the specified server
13232. List available tools
13243. Start an interactive chat session where you can:
1325 * Enter queries
1326 * See tool executions
1327 * Get responses from Claude
1328 
1329## How it works
1330 
1331Here's a high-level workflow schema:
1332 
1333```mermaid theme={null}
1334---
1335config:
1336 theme: neutral
1337---
1338sequenceDiagram
1339 actor User
1340 participant Client
1341 participant Claude
1342 participant MCP_Server as MCP Server
1343 participant Tools
1344 
1345 User->>Client: Send query
1346 Client<<->>MCP_Server: Get available tools
1347 Client->>Claude: Send query with tool descriptions
1348 Claude-->>Client: Decide tool execution
1349 Client->>MCP_Server: Request tool execution
1350 MCP_Server->>Tools: Execute chosen tools
1351 Tools-->>MCP_Server: Return results
1352 MCP_Server-->>Client: Send results
1353 Client->>Claude: Send tool results
1354 Claude-->>Client: Provide final response
1355 Client-->>User: Display response
1356```
1357 
1358When you submit a query:
1359 
13601. The client gets the list of available tools from the server
13612. Your query is sent to Claude along with tool descriptions
13623. Claude decides which tools (if any) to use
13634. The client executes any requested tool calls through the server
13645. Results are sent back to Claude
13656. Claude provides a natural language response
13667. The response is displayed to you
1367 
1368## Best practices
1369 
13701. **Error Handling**
1371 * Leverage Kotlin's type system to model errors explicitly
1372 * Wrap external tool and API calls in `try-catch` blocks when exceptions are possible
1373 * Provide clear and meaningful error messages
1374 * Handle network timeouts and connection issues gracefully
1375 
13762. **Security**
1377 * Store API keys and secrets securely in `local.properties`, environment variables, or secret managers
1378 * Validate all external responses to avoid unexpected or unsafe data usage
1379 * Be cautious with permissions and trust boundaries when using tools
1380 
13813. **Environment**
1382 * Set `ANTHROPIC_API_KEY` through environment variables rather than hardcoding
1383 * Use `.env` files with appropriate `.gitignore` rules for local development
1384 
1385## Troubleshooting
1386 
1387### Server Path Issues
1388 
1389* Double-check the path to your server script is correct
1390* Use the absolute path if the relative path isn't working
1391* For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
1392* Make sure that the required runtime is installed (java for Java, npm for Node.js, or uv for Python)
1393* Verify the server file has the correct extension (.jar for Java, .js for Node.js or .py for Python)
1394 
1395Example of correct path usage:
1396 
1397```bash theme={null}
1398# Relative path
1399java -jar build/libs/client.jar ./server/build/libs/server.jar
1400 
1401# Absolute path
1402java -jar build/libs/client.jar /Users/username/projects/mcp-server/build/libs/server.jar
1403 
1404# Windows path (either format works)
1405java -jar build/libs/client.jar C:/projects/mcp-server/build/libs/server.jar
1406java -jar build/libs/client.jar C:\\projects\\mcp-server\\build\\libs\\server.jar
1407```
1408 
1409### Build Issues
1410 
1411* Use `./gradlew build` or `./gradlew shadowJar` (not `./gradlew jar`) to create the shadow JAR with all dependencies
1412* If you get JDK version errors, ensure your installed JDK version matches or exceeds the `jvmToolchain` setting in `build.gradle.kts`
1413 
1414### Response Timing
1415 
1416* The first response might take up to 30 seconds to return
1417* This is normal and happens while:
1418 * The server initializes
1419 * Claude processes the query
1420 * Tools are being executed
1421* Subsequent responses are typically faster
1422* Don't interrupt the process during this initial waiting period
1423 
1424### Common Error Messages
1425 
1426If you see:
1427 
1428* `Connection refused`: Ensure the server is running and the path is correct
1429* `Tool execution failed`: Verify the tool's required environment variables are set
1430* `ANTHROPIC_API_KEY is not set`: Check your environment variables
1431 
1432**C#**
1433 
1434[You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/csharp-sdk/tree/main/samples/QuickstartClient)
1435 
1436## System Requirements
1437 
1438Before starting, ensure your system meets these requirements:
1439 
1440* .NET 8.0 or higher
1441* Anthropic API key (Claude)
1442* Windows, Linux, or macOS
1443 
1444## Setting up your environment
1445 
1446First, create a new .NET project:
1447 
1448```bash theme={null}
1449dotnet new console -n QuickstartClient
1450cd QuickstartClient
1451```
1452 
1453Then, add the required dependencies to your project:
1454 
1455```bash theme={null}
1456dotnet add package ModelContextProtocol --prerelease
1457dotnet add package Anthropic.SDK
1458dotnet add package Microsoft.Extensions.Hosting
1459dotnet add package Microsoft.Extensions.AI
1460```
1461 
1462## Setting up your API key
1463 
1464You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
1465 
1466```bash theme={null}
1467dotnet user-secrets init
1468dotnet user-secrets set "ANTHROPIC_API_KEY" "<your key here>"
1469```
1470 
1471## Creating the Client
1472 
1473### Basic Client Structure
1474 
1475First, let's setup the basic client class in the file `Program.cs`:
1476 
1477```csharp theme={null}
1478using Anthropic.SDK;
1479using Microsoft.Extensions.AI;
1480using Microsoft.Extensions.Configuration;
1481using Microsoft.Extensions.Hosting;
1482using ModelContextProtocol.Client;
1483using ModelContextProtocol.Protocol.Transport;
1484 
1485var builder = Host.CreateApplicationBuilder(args);
1486 
1487builder.Configuration
1488 .AddEnvironmentVariables()
1489 .AddUserSecrets<Program>();
1490```
1491 
1492This creates the beginnings of a .NET console application that can read the API key from user secrets.
1493 
1494Next, we'll setup the MCP Client:
1495 
1496```csharp theme={null}
1497var (command, arguments) = GetCommandAndArguments(args);
1498 
1499var clientTransport = new StdioClientTransport(new()
1500{
1501 Name = "Demo Server",
1502 Command = command,
1503 Arguments = arguments,
1504});
1505 
1506await using var mcpClient = await McpClient.CreateAsync(clientTransport);
1507 
1508var tools = await mcpClient.ListToolsAsync();
1509foreach (var tool in tools)
1510{
1511 Console.WriteLine($"Connected to server with tools: {tool.Name}");
1512}
1513```
1514 
1515Add this function at the end of the `Program.cs` file:
1516 
1517```csharp theme={null}
1518static (string command, string[] arguments) GetCommandAndArguments(string[] args)
1519{
1520 return args switch
15081521 {
1509 Name = "Demo Server",
1510 Command = command,
1511 Arguments = arguments,
1512 });
1513 
1514 await using var mcpClient = await McpClient.CreateAsync(clientTransport);
1515 
1516 var tools = await mcpClient.ListToolsAsync();
1517 foreach (var tool in tools)
1522 [var script] when script.EndsWith(".py") => ("python", args),
1523 [var script] when script.EndsWith(".js") => ("node", args),
1524 [var script] when Directory.Exists(script) || (File.Exists(script) && script.EndsWith(".csproj")) => ("dotnet", ["run", "--project", script, "--no-build"]),
1525 _ => throw new NotSupportedException("An unsupported server script was provided. Supported scripts are .py, .js, or .csproj")
1526 };
1527}
1528```
1529 
1530This creates an MCP client that will connect to a server that is provided as a command line argument. It then lists the available tools from the connected server.
1531 
1532### Query processing logic
1533 
1534Now let's add the core functionality for processing queries and handling tool calls:
1535 
1536```csharp theme={null}
1537using var anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration["ANTHROPIC_API_KEY"]))
1538 .Messages
1539 .AsBuilder()
1540 .UseFunctionInvocation()
1541 .Build();
1542 
1543var options = new ChatOptions
1544{
1545 MaxOutputTokens = 1000,
1546 ModelId = "claude-sonnet-4-20250514",
1547 Tools = [.. tools]
1548};
1549 
1550Console.ForegroundColor = ConsoleColor.Green;
1551Console.WriteLine("MCP Client Started!");
1552Console.ResetColor();
1553 
1554PromptForInput();
1555while(Console.ReadLine() is string query && !"exit".Equals(query, StringComparison.OrdinalIgnoreCase))
1556{
1557 if (string.IsNullOrWhiteSpace(query))
15181558 {
1519 Console.WriteLine($"Connected to server with tools: {tool.Name}");
1559 PromptForInput();
1560 continue;
15201561 }
1521 ```
1522 
1523 Add this function at the end of the `Program.cs` file:
1524 
1525 ```csharp theme={null}
1526 static (string command, string[] arguments) GetCommandAndArguments(string[] args)
1562 
1563 await foreach (var message in anthropicClient.GetStreamingResponseAsync(query, options))
15271564 {
1528 return args switch
1529 {
1530 [var script] when script.EndsWith(".py") => ("python", args),
1531 [var script] when script.EndsWith(".js") => ("node", args),
1532 [var script] when Directory.Exists(script) || (File.Exists(script) && script.EndsWith(".csproj")) => ("dotnet", ["run", "--project", script, "--no-build"]),
1533 _ => throw new NotSupportedException("An unsupported server script was provided. Supported scripts are .py, .js, or .csproj")
1534 };
1565 Console.Write(message);
15351566 }
1536 ```
1537 
1538 This creates an MCP client that will connect to a server that is provided as a command line argument. It then lists the available tools from the connected server.
1539 
1540 ### Query processing logic
1541 
1542 Now let's add the core functionality for processing queries and handling tool calls:
1543 
1544 ```csharp theme={null}
1545 using var anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration["ANTHROPIC_API_KEY"]))
1546 .Messages
1547 .AsBuilder()
1548 .UseFunctionInvocation()
1549 .Build();
1550 
1551 var options = new ChatOptions
1552 {
1553 MaxOutputTokens = 1000,
1554 ModelId = "claude-sonnet-4-20250514",
1555 Tools = [.. tools]
1556 };
1557 
1558 Console.ForegroundColor = ConsoleColor.Green;
1559 Console.WriteLine("MCP Client Started!");
1567 Console.WriteLine();
1568 
1569 PromptForInput();
1570}
1571 
1572static void PromptForInput()
1573{
1574 Console.WriteLine("Enter a command (or 'exit' to quit):");
1575 Console.ForegroundColor = ConsoleColor.Cyan;
1576 Console.Write("> ");
15601577 Console.ResetColor();
1561 
1562 PromptForInput();
1563 while(Console.ReadLine() is string query && !"exit".Equals(query, StringComparison.OrdinalIgnoreCase))
1564 {
1565 if (string.IsNullOrWhiteSpace(query))
1566 {
1567 PromptForInput();
1568 continue;
1569 }
1570 
1571 await foreach (var message in anthropicClient.GetStreamingResponseAsync(query, options))
1572 {
1573 Console.Write(message);
1574 }
1575 Console.WriteLine();
1576 
1577 PromptForInput();
1578 }
1579 
1580 static void PromptForInput()
1581 {
1582 Console.WriteLine("Enter a command (or 'exit' to quit):");
1583 Console.ForegroundColor = ConsoleColor.Cyan;
1584 Console.Write("> ");
1585 Console.ResetColor();
1586 }
1587 ```
1588 
1589 ## Key Components Explained
1590 
1591 ### 1. Client Initialization
1592 
1593 * The client is initialized using `McpClient.CreateAsync()`, which sets up the transport type and command to run the server.
1594 
1595 ### 2. Server Connection
1596 
1597 * Supports Python, Node.js, and .NET servers.
1598 * The server is started using the command specified in the arguments.
1599 * Configures to use stdio for communication with the server.
1600 * Initializes the session and available tools.
1601 
1602 ### 3. Query Processing
1603 
1604 * Leverages [Microsoft.Extensions.AI](https://learn.microsoft.com/dotnet/ai/ai-extensions) for the chat client.
1605 * Configures the `IChatClient` to use automatic tool (function) invocation.
1606 * The client reads user input and sends it to the server.
1607 * The server processes the query and returns a response.
1608 * The response is displayed to the user.
1609 
1610 ## Running the Client
1611 
1612 To run your client with any MCP server:
1613 
1614 ```bash theme={null}
1615 dotnet run -- path/to/server.csproj # dotnet server
1616 dotnet run -- path/to/server.py # python server
1617 dotnet run -- path/to/server.js # node server
1618 ```
1619 
1620 <Note>
1621 If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `dotnet run -- path/to/QuickstartWeatherServer`.
1622 </Note>
1623 
1624 The client will:
1625 
1626 1. Connect to the specified server
1627 2. List available tools
1628 3. Start an interactive chat session where you can:
1629 * Enter queries
1630 * See tool executions
1631 * Get responses from Claude
1632 4. Exit the session when done
1633 
1634 Here's an example of what it should look like if connected to the weather server quickstart:
1635 
1636 <Frame>
1637 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-dotnet-client.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=fcf28dde150d6db879402ad8150c6b23" width="1115" height="666" data-path="images/quickstart-dotnet-client.png" />
1638 </Frame>
1639 </Tab>
1640 
1641 <Tab title="Ruby">
1642 [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-ruby)
1643 
1644 ## System Requirements
1645 
1646 Before starting, ensure your system meets these requirements:
1647 
1648 * Mac or Windows computer
1649 * Ruby 3.2.0 or higher installed (required by the [Anthropic SDK](https://github.com/anthropics/anthropic-sdk-ruby))
1650 * Anthropic API key (Claude)
1651 
1652 ## Setting Up Your Environment
1653 
1654 First, create a new Ruby project:
1655 
1656 <CodeGroup>
1657 ```bash macOS/Linux theme={null}
1658 # Create project directory
1659 mkdir mcp-client
1660 cd mcp-client
1661 
1662 # Create a Gemfile
1663 bundle init
1664 
1665 # Add required dependencies
1666 bundle add anthropic base64 dotenv mcp
1667 
1668 # Create our main file
1669 touch client.rb
1670 ```
1671 
1672 ```powershell Windows theme={null}
1673 # Create project directory
1674 mkdir mcp-client
1675 cd mcp-client
1676 
1677 # Create a Gemfile
1678 bundle init
1679 
1680 # Add required dependencies
1681 bundle add anthropic base64 dotenv mcp
1682 
1683 # Create our main file
1684 new-item client.rb
1685 ```
1686 </CodeGroup>
1687 
1688 ## Setting Up Your API Key
1689 
1690 You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
1691 
1692 Create a `.env` file to store it:
1693 
1694 ```bash theme={null}
1695 echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env
1696 ```
1697 
1698 Add `.env` to your `.gitignore`:
1699 
1700 ```bash theme={null}
1701 echo ".env" >> .gitignore
1702 ```
1703 
1704 <Warning>
1705 Make sure you keep your `ANTHROPIC_API_KEY` secure!
1706 </Warning>
1707 
1708 ## Creating the Client
1709 
1710 ### Basic Client Structure
1711 
1712 First, let's set up our requires and create the basic client class:
1713 
1714 ```ruby theme={null}
1715 require "anthropic"
1716 require "dotenv/load"
1717 require "json"
1718 require "mcp"
1719 
1720 class MCPClient
1721 ANTHROPIC_MODEL = "claude-sonnet-4-20250514"
1722 
1723 def initialize
1724 @mcp_client = nil
1725 @transport = nil
1726 @anthropic_client = nil
1727 end
1728 
1729 # methods will go here
1730 end
1731 ```
1732 
1733 ### Server Connection Management
1734 
1735 Next, we'll implement the method to connect to an MCP server:
1736 
1737 ```ruby theme={null}
1738 def connect_to_server(server_script_path)
1739 command = case File.extname(server_script_path)
1740 when ".rb"
1741 "ruby"
1742 when ".py"
1743 "python3"
1744 when ".js"
1745 "node"
1746 else
1747 raise ArgumentError, "Server script must be a .rb, .py, or .js file."
1748 end
1749 
1750 @transport = MCP::Client::Stdio.new(command: command, args: [server_script_path])
1751 @mcp_client = MCP::Client.new(transport: @transport)
1752 @mcp_client.connect
1753 
1754 tool_names = @mcp_client.tools.map(&:name)
1755 puts "\nConnected to server with tools: #{tool_names}"
1756 end
1757 ```
1758 
1759 ### Query Processing Logic
1760 
1761 Now let's add the core functionality for processing queries and handling tool calls:
1762 
1763 ```ruby theme={null}
1764 private
1765 
1766 def process_query(query)
1767 messages = [{ role: "user", content: query }]
1768 
1769 available_tools = @mcp_client.tools.map do |tool|
1770 { name: tool.name, description: tool.description, input_schema: tool.input_schema }
1771 end
1772 
1773 # Initial Claude API call.
1774 response = chat(messages, tools: available_tools)
1775 
1776 # Process response and handle tool calls.
1777 if response.content.any?(Anthropic::Models::ToolUseBlock)
1778 assistant_content = response.content.filter_map do |content_block|
1779 case content_block
1780 when Anthropic::Models::TextBlock
1781 { type: "text", text: content_block.text }
1782 when Anthropic::Models::ToolUseBlock
1783 { type: "tool_use", id: content_block.id, name: content_block.name, input: content_block.input }
1784 end
1785 end
1786 messages << { role: "assistant", content: assistant_content }
1787 end
1788 
1789 response.content.each_with_object([]) do |content, response_parts|
1790 case content
1791 when Anthropic::Models::TextBlock
1792 response_parts << content.text
1793 when Anthropic::Models::ToolUseBlock
1794 # Execute tool call via MCP.
1795 result = @mcp_client.call_tool(name: content.name, arguments: content.input)
1796 response_parts << "[Calling tool #{content.name} with args #{content.input.to_json}]"
1797 
1798 tool_result_content = result.dig("result", "content")
1799 result_text = if tool_result_content.is_a?(Array)
1800 tool_result_content.filter_map { |content_item| content_item["text"] }.join("\n")
1801 else
1802 tool_result_content.to_s
1803 end
1804 
1805 messages << {
1806 role: "user",
1807 content: [{
1808 type: "tool_result",
1809 tool_use_id: content.id,
1810 content: result_text
1811 }]
1812 }
1813 
1814 # Get next response from Claude.
1815 response = chat(messages)
1816 
1817 response.content.each do |content_block|
1818 response_parts << content_block.text if content_block.is_a?(Anthropic::Models::TextBlock)
1819 end
1820 end
1821 end.join("\n")
1822 end
1823 
1824 def chat(messages, tools: nil)
1825 params = { model: ANTHROPIC_MODEL, max_tokens: 1000, messages: messages }
1826 params[:tools] = tools if tools
1827 
1828 anthropic_client.messages.create(**params)
1829 end
1830 
1831 def anthropic_client
1832 @anthropic_client ||= Anthropic::Client.new(api_key: ENV["ANTHROPIC_API_KEY"])
1833 end
1834 ```
1835 
1836 ### Interactive Chat Interface
1837 
1838 Now we'll add the chat loop and cleanup functionality:
1839 
1840 ```ruby theme={null}
1841 def chat_loop
1842 puts <<~MESSAGE
1843 MCP Client Started!
1844 Type your queries or 'quit' to exit.
1845 MESSAGE
1846 
1847 loop do
1848 print "\nQuery: "
1849 line = $stdin.gets
1850 break if line.nil?
1851 
1852 query = line.chomp.strip
1853 break if query.downcase == "quit"
1854 next if query.empty?
1855 
1856 begin
1857 response = process_query(query)
1858 puts "\n#{response}"
1859 rescue => e
1860 puts "\nError: #{e.message}"
1861 end
1578}
1579```
1580 
1581## Key Components Explained
1582 
1583### 1. Client Initialization
1584 
1585* The client is initialized using `McpClient.CreateAsync()`, which sets up the transport type and command to run the server.
1586 
1587### 2. Server Connection
1588 
1589* Supports Python, Node.js, and .NET servers.
1590* The server is started using the command specified in the arguments.
1591* Configures to use stdio for communication with the server.
1592* Initializes the session and available tools.
1593 
1594### 3. Query Processing
1595 
1596* Leverages [Microsoft.Extensions.AI](https://learn.microsoft.com/dotnet/ai/ai-extensions) for the chat client.
1597* Configures the `IChatClient` to use automatic tool (function) invocation.
1598* The client reads user input and sends it to the server.
1599* The server processes the query and returns a response.
1600* The response is displayed to the user.
1601 
1602## Running the Client
1603 
1604To run your client with any MCP server:
1605 
1606```bash theme={null}
1607dotnet run -- path/to/server.csproj # dotnet server
1608dotnet run -- path/to/server.py # python server
1609dotnet run -- path/to/server.js # node server
1610```
1611 
1612> [!NOTE]
1613>
1614> If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `dotnet run -- path/to/QuickstartWeatherServer`.
1615 
1616The client will:
1617 
16181. Connect to the specified server
16192. List available tools
16203. Start an interactive chat session where you can:
1621 * Enter queries
1622 * See tool executions
1623 * Get responses from Claude
16244. Exit the session when done
1625 
1626Here's an example of what it should look like if connected to the weather server quickstart:
1627 
1628![](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-dotnet-client.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=fcf28dde150d6db879402ad8150c6b23)
1629 
1630**Ruby**
1631 
1632[You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-ruby)
1633 
1634## System Requirements
1635 
1636Before starting, ensure your system meets these requirements:
1637 
1638* Mac or Windows computer
1639* Ruby 3.2.0 or higher installed (required by the [Anthropic SDK](https://github.com/anthropics/anthropic-sdk-ruby))
1640* Anthropic API key (Claude)
1641 
1642## Setting Up Your Environment
1643 
1644First, create a new Ruby project:
1645 
1646```bash macOS/Linux theme={null}
1647# Create project directory
1648mkdir mcp-client
1649cd mcp-client
1650 
1651# Create a Gemfile
1652bundle init
1653 
1654# Add required dependencies
1655bundle add anthropic base64 dotenv mcp
1656 
1657# Create our main file
1658touch client.rb
1659```
1660 
1661```powershell Windows theme={null}
1662# Create project directory
1663mkdir mcp-client
1664cd mcp-client
1665 
1666# Create a Gemfile
1667bundle init
1668 
1669# Add required dependencies
1670bundle add anthropic base64 dotenv mcp
1671 
1672# Create our main file
1673new-item client.rb
1674```
1675 
1676## Setting Up Your API Key
1677 
1678You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
1679 
1680Create a `.env` file to store it:
1681 
1682```bash theme={null}
1683echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env
1684```
1685 
1686Add `.env` to your `.gitignore`:
1687 
1688```bash theme={null}
1689echo ".env" >> .gitignore
1690```
1691 
1692> [!WARNING]
1693>
1694> Make sure you keep your `ANTHROPIC_API_KEY` secure!
1695 
1696## Creating the Client
1697 
1698### Basic Client Structure
1699 
1700First, let's set up our requires and create the basic client class:
1701 
1702```ruby theme={null}
1703require "anthropic"
1704require "dotenv/load"
1705require "json"
1706require "mcp"
1707 
1708class MCPClient
1709 ANTHROPIC_MODEL = "claude-sonnet-4-20250514"
1710 
1711 def initialize
1712 @mcp_client = nil
1713 @transport = nil
1714 @anthropic_client = nil
1715 end
1716 
1717 # methods will go here
1718end
1719```
1720 
1721### Server Connection Management
1722 
1723Next, we'll implement the method to connect to an MCP server:
1724 
1725```ruby theme={null}
1726def connect_to_server(server_script_path)
1727 command = case File.extname(server_script_path)
1728 when ".rb"
1729 "ruby"
1730 when ".py"
1731 "python3"
1732 when ".js"
1733 "node"
1734 else
1735 raise ArgumentError, "Server script must be a .rb, .py, or .js file."
1736 end
1737 
1738 @transport = MCP::Client::Stdio.new(command: command, args: [server_script_path])
1739 @mcp_client = MCP::Client.new(transport: @transport)
1740 @mcp_client.connect
1741 
1742 tool_names = @mcp_client.tools.map(&:name)
1743 puts "\nConnected to server with tools: #{tool_names}"
1744end
1745```
1746 
1747### Query Processing Logic
1748 
1749Now let's add the core functionality for processing queries and handling tool calls:
1750 
1751```ruby theme={null}
1752private
1753 
1754def process_query(query)
1755 messages = [{ role: "user", content: query }]
1756 
1757 available_tools = @mcp_client.tools.map do |tool|
1758 { name: tool.name, description: tool.description, input_schema: tool.input_schema }
1759 end
1760 
1761 # Initial Claude API call.
1762 response = chat(messages, tools: available_tools)
1763 
1764 # Process response and handle tool calls.
1765 if response.content.any?(Anthropic::Models::ToolUseBlock)
1766 assistant_content = response.content.filter_map do |content_block|
1767 case content_block
1768 when Anthropic::Models::TextBlock
1769 { type: "text", text: content_block.text }
1770 when Anthropic::Models::ToolUseBlock
1771 { type: "tool_use", id: content_block.id, name: content_block.name, input: content_block.input }
18621772 end
18631773 end
1864 
1865 def cleanup
1866 @transport&.close
1774 messages << { role: "assistant", content: assistant_content }
1775 end
1776 
1777 response.content.each_with_object([]) do |content, response_parts|
1778 case content
1779 when Anthropic::Models::TextBlock
1780 response_parts << content.text
1781 when Anthropic::Models::ToolUseBlock
1782 # Execute tool call via MCP.
1783 result = @mcp_client.call_tool(name: content.name, arguments: content.input)
1784 response_parts << "[Calling tool #{content.name} with args #{content.input.to_json}]"
1785 
1786 tool_result_content = result.dig("result", "content")
1787 result_text = if tool_result_content.is_a?(Array)
1788 tool_result_content.filter_map { |content_item| content_item["text"] }.join("\n")
1789 else
1790 tool_result_content.to_s
1791 end
1792 
1793 messages << {
1794 role: "user",
1795 content: [{
1796 type: "tool_result",
1797 tool_use_id: content.id,
1798 content: result_text
1799 }]
1800 }
1801 
1802 # Get next response from Claude.
1803 response = chat(messages)
1804 
1805 response.content.each do |content_block|
1806 response_parts << content_block.text if content_block.is_a?(Anthropic::Models::TextBlock)
1807 end
18671808 end
1868 ```
1869 
1870 ### Main Entry Point
1871 
1872 Finally, we'll add the main execution logic:
1873 
1874 ```ruby theme={null}
1875 if ARGV.empty?
1876 puts "Usage: ruby client.rb <path_to_server_script>"
1877 exit 1
1809 end.join("\n")
1810end
1811 
1812def chat(messages, tools: nil)
1813 params = { model: ANTHROPIC_MODEL, max_tokens: 1000, messages: messages }
1814 params[:tools] = tools if tools
1815 
1816 anthropic_client.messages.create(**params)
1817end
1818 
1819def anthropic_client
1820 @anthropic_client ||= Anthropic::Client.new(api_key: ENV["ANTHROPIC_API_KEY"])
1821end
1822```
1823 
1824### Interactive Chat Interface
1825 
1826Now we'll add the chat loop and cleanup functionality:
1827 
1828```ruby theme={null}
1829def chat_loop
1830 puts <<~MESSAGE
1831 MCP Client Started!
1832 Type your queries or 'quit' to exit.
1833 MESSAGE
1834 
1835 loop do
1836 print "\nQuery: "
1837 line = $stdin.gets
1838 break if line.nil?
1839 
1840 query = line.chomp.strip
1841 break if query.downcase == "quit"
1842 next if query.empty?
1843 
1844 begin
1845 response = process_query(query)
1846 puts "\n#{response}"
1847 rescue => e
1848 puts "\nError: #{e.message}"
18781849 end
1879 
1880 client = MCPClient.new
1881 
1882 begin
1883 client.connect_to_server(ARGV[0])
1884 
1885 api_key = ENV["ANTHROPIC_API_KEY"]
1886 if api_key.nil? || api_key.empty?
1887 puts <<~MESSAGE
1888 No ANTHROPIC_API_KEY found. To query these tools with Claude, set your API key:
1889 export ANTHROPIC_API_KEY=your-api-key-here
1890 MESSAGE
1891 exit
1892 end
1893 
1894 client.chat_loop
1895 rescue => e
1896 puts "Error: #{e.message}"
1897 exit 1
1898 ensure
1899 client.cleanup
1900 end
1901 ```
1902 
1903 You can find the complete `client.rb` file [here](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-ruby/client.rb).
1904 
1905 ## Key Components Explained
1906 
1907 ### 1. Client Initialization
1908 
1909 * The `MCPClient` class initializes with nil references for lazy setup
1910 * The Anthropic client is lazily initialized via the `anthropic_client` method
1911 * Uses `dotenv` to load environment variables from `.env`
1912 
1913 ### 2. Server Connection
1914 
1915 * Supports Ruby, Python, and Node.js servers
1916 * Uses `File.extname` to determine the server script type
1917 * Uses `MCP::Client::Stdio` for stdio transport
1918 * Initializes the MCP client and lists available tools
1919 
1920 ### 3. Query Processing
1921 
1922 * Maps MCP tools to Anthropic tool format (`name`, `description`, `input_schema`)
1923 * Uses `Anthropic::Models::TextBlock` and `Anthropic::Models::ToolUseBlock` for pattern matching
1924 * Builds assistant content once before iterating tool calls
1925 * Executes tool calls via `@mcp_client.call_tool`
1926 * Uses `chat` helper method to wrap Anthropic API calls
1927 * Extracts tool result content with `result.dig("result", "content")`
1928 * Passes tool results back to Claude for a final response
1929 
1930 ### 4. Interactive Interface
1931 
1932 * Provides a simple command-line interface
1933 * Handles user input and displays responses
1934 * Skips empty queries
1935 * Includes basic error handling
1936 
1937 ### 5. Resource Management
1938 
1939 * Proper cleanup of the transport via `begin`...`ensure`
1940 * Top-level `rescue` for error handling
1941 * API key validation after server connection
1942 
1943 ## Running the Client
1944 
1945 To run your client with any MCP server:
1946 
1947 ```bash theme={null}
1948 bundle exec ruby client.rb path/to/server.rb # ruby server
1949 bundle exec ruby client.rb path/to/server.py # python server
1950 bundle exec ruby client.rb path/to/build/index.js # node server
1951 ```
1952 
1953 <Note>
1954 If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-ruby), your command might look something like this: `bundle exec ruby client.rb /path/to/weather-server-ruby/weather.rb`
1955 </Note>
1956 
1957 The client will:
1958 
1959 1. Connect to the specified server
1960 2. List available tools
1961 3. Start an interactive chat session where you can:
1962 * Enter queries
1963 * See tool executions
1964 * Get responses from Claude
1965 
1966 ## How It Works
1967 
1968 When you submit a query:
1969 
1970 1. The client gets the list of available tools from the server
1971 2. Your query is sent to Claude along with tool descriptions
1972 3. Claude decides which tools (if any) to use
1973 4. The client executes any requested tool calls through the server
1974 5. Results are sent back to Claude
1975 6. Claude provides a natural language response
1976 7. The response is displayed to you
1977 
1978 ## Best practices
1979 
1980 1. **Error Handling**
1981 * Wrap tool calls in `begin`...`rescue` blocks
1982 * Provide meaningful error messages
1983 * Gracefully handle connection issues
1984 
1985 2. **Resource Management**
1986 * Always close the transport when done
1987 * Use `begin`...`ensure` for proper cleanup
1988 * Handle server disconnections
1989 
1990 3. **Security**
1991 * Store API keys securely in `.env`
1992 * Validate server responses
1993 * Be cautious with tool permissions
1994 
1995 4. **Tool Names**
1996 * Tool names can be validated according to the format specified [here](/specification/2025-11-25/server/tools#tool-names)
1997 * If a tool name conforms to the specified format, it should not fail validation by an MCP client
1998 
1999 ## Troubleshooting
2000 
2001 ### Server Path Issues
2002 
2003 * Double-check the path to your server script is correct
2004 * Use the absolute path if the relative path isn't working
2005 * For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
2006 * Verify the server file has the correct extension (.py for Python, .js for Node.js, or .rb for Ruby)
2007 
2008 Example of correct path usage:
2009 
2010 ```bash theme={null}
2011 # Relative path
2012 bundle exec ruby client.rb ./server/weather.rb
2013 
2014 # Absolute path
2015 bundle exec ruby client.rb /Users/username/projects/mcp-server/weather.rb
2016 
2017 # Windows path (either format works)
2018 bundle exec ruby client.rb C:/projects/mcp-server/weather.rb
2019 bundle exec ruby client.rb C:\\projects\\mcp-server\\weather.rb
2020 ```
2021 
2022 ### Response Timing
2023 
2024 * The first response might take up to 30 seconds to return
2025 * This is normal and happens while:
2026 * The server initializes
2027 * Claude processes the query
2028 * Tools are being executed
2029 * Subsequent responses are typically faster
2030 * Don't interrupt the process during this initial waiting period
2031 
2032 ### Common Error Messages
2033 
2034 If you see:
2035 
2036 * `Errno::ENOENT`: Check your server path and ensure the command (`ruby`, `python3`, `node`) is available
2037 * `Connection refused`: Ensure the server is running and the path is correct
2038 * `Tool execution failed`: Verify the tool's required environment variables are set
2039 * `Anthropic::Errors::AuthenticationError`: Check your `.env` file has a valid `ANTHROPIC_API_KEY`
2040 </Tab>
2041 
2042 <Tab title="Rust">
2043 [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-rust)
2044 
2045 ## System Requirements
2046 
2047 Before starting, ensure your Linux system meets these requirements:
2048 
2049 * Latest stable version of [Rust and Cargo](https://www.rust-lang.org/tools/install)
2050 * Anthropic API key (Claude)
2051 * A Python, Node.js, or executable MCP server to connect to
2052 
2053 ## Setting Up Your Environment
2054 
2055 First, create a new Rust project:
2056 
2057 ```bash theme={null}
2058 cargo new mcp-client-rust
2059 cd mcp-client-rust
2060 ```
2061 
2062 Replace the contents of `Cargo.toml` with the following:
2063 
2064 ```toml Cargo.toml theme={null}
2065 [package]
2066 name = "mcp-client-rust"
2067 version = "0.1.0"
2068 edition = "2024"
2069 
2070 [dependencies]
2071 anyhow = "1.0.100"
2072 genai = "0.4.2"
2073 rmcp = { version = "0.8.0", features = ["server", "client", "transport-io", "transport-child-process"] }
2074 tokio = { version = "1.47.1", features = ["full"] }
2075 tracing = "0.1.41"
2076 tracing-subscriber = { version = "0.3", features = ["env-filter"] }
2077 serde_json = "1.0.128"
2078 dotenvy = "0.15.7"
2079 reqwest = "0.12.23"
2080 ```
2081 
2082 The [`rmcp`](https://github.com/modelcontextprotocol/rust-sdk) crate provides the Rust MCP SDK and child-process transport. This example uses the [`genai`](https://github.com/jeremychone/rust-genai) crate to send requests to Claude and represent tools in the model request.
2083 
2084 ## Setting Up Your API Key
2085 
2086 You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
2087 
2088 Create a `.env` file to store it:
2089 
2090 ```bash theme={null}
2091 echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env
2092 ```
2093 
2094 Add `.env` to your `.gitignore`:
2095 
2096 ```bash theme={null}
2097 echo ".env" >> .gitignore
2098 ```
2099 
2100 <Warning>
2101 Make sure you keep your `ANTHROPIC_API_KEY` secure!
2102 </Warning>
2103 
2104 ## Creating the Client
2105 
2106 Open `src/main.rs` and replace its contents as you work through the following sections.
2107 
2108 ### Imports and Client Structure
2109 
2110 First, add the imports, model constant, and basic client structure:
2111 
2112 ```rust theme={null}
2113 use anyhow::{Context, Result, bail};
2114 use genai::Client;
2115 use genai::chat::{
2116 ChatMessage, ChatRequest, ChatResponse, ContentPart, Tool as GenaiTool, ToolResponse,
2117 };
2118 use rmcp::model::{CallToolRequestParam, Tool as McpTool};
2119 use rmcp::service::{RoleClient, RunningService, ServiceExt};
2120 use rmcp::transport::TokioChildProcess;
2121 use serde_json::Value;
2122 use tokio::io::{self, AsyncBufReadExt, BufReader};
2123 use tokio::process::Command;
2124 
2125 const MODEL_ANTHROPIC: &str = "claude-sonnet-4-20250514";
2126 
2127 struct MCPClient {
2128 anthropic: Client,
2129 session: Option<RunningService<RoleClient, ()>>,
2130 tools: Vec<GenaiTool>,
1850 end
1851end
1852 
1853def cleanup
1854 @transport&.close
1855end
1856```
1857 
1858### Main Entry Point
1859 
1860Finally, we'll add the main execution logic:
1861 
1862```ruby theme={null}
1863if ARGV.empty?
1864 puts "Usage: ruby client.rb <path_to_server_script>"
1865 exit 1
1866end
1867 
1868client = MCPClient.new
1869 
1870begin
1871 client.connect_to_server(ARGV[0])
1872 
1873 api_key = ENV["ANTHROPIC_API_KEY"]
1874 if api_key.nil? || api_key.empty?
1875 puts <<~MESSAGE
1876 No ANTHROPIC_API_KEY found. To query these tools with Claude, set your API key:
1877 export ANTHROPIC_API_KEY=your-api-key-here
1878 MESSAGE
1879 exit
1880 end
1881 
1882 client.chat_loop
1883rescue => e
1884 puts "Error: #{e.message}"
1885 exit 1
1886ensure
1887 client.cleanup
1888end
1889```
1890 
1891You can find the complete `client.rb` file [here](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-ruby/client.rb).
1892 
1893## Key Components Explained
1894 
1895### 1. Client Initialization
1896 
1897* The `MCPClient` class initializes with nil references for lazy setup
1898* The Anthropic client is lazily initialized via the `anthropic_client` method
1899* Uses `dotenv` to load environment variables from `.env`
1900 
1901### 2. Server Connection
1902 
1903* Supports Ruby, Python, and Node.js servers
1904* Uses `File.extname` to determine the server script type
1905* Uses `MCP::Client::Stdio` for stdio transport
1906* Initializes the MCP client and lists available tools
1907 
1908### 3. Query Processing
1909 
1910* Maps MCP tools to Anthropic tool format (`name`, `description`, `input_schema`)
1911* Uses `Anthropic::Models::TextBlock` and `Anthropic::Models::ToolUseBlock` for pattern matching
1912* Builds assistant content once before iterating tool calls
1913* Executes tool calls via `@mcp_client.call_tool`
1914* Uses `chat` helper method to wrap Anthropic API calls
1915* Extracts tool result content with `result.dig("result", "content")`
1916* Passes tool results back to Claude for a final response
1917 
1918### 4. Interactive Interface
1919 
1920* Provides a simple command-line interface
1921* Handles user input and displays responses
1922* Skips empty queries
1923* Includes basic error handling
1924 
1925### 5. Resource Management
1926 
1927* Proper cleanup of the transport via `begin`...`ensure`
1928* Top-level `rescue` for error handling
1929* API key validation after server connection
1930 
1931## Running the Client
1932 
1933To run your client with any MCP server:
1934 
1935```bash theme={null}
1936bundle exec ruby client.rb path/to/server.rb # ruby server
1937bundle exec ruby client.rb path/to/server.py # python server
1938bundle exec ruby client.rb path/to/build/index.js # node server
1939```
1940 
1941> [!NOTE]
1942>
1943> If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-ruby), your command might look something like this: `bundle exec ruby client.rb /path/to/weather-server-ruby/weather.rb`
1944 
1945The client will:
1946 
19471. Connect to the specified server
19482. List available tools
19493. Start an interactive chat session where you can:
1950 * Enter queries
1951 * See tool executions
1952 * Get responses from Claude
1953 
1954## How It Works
1955 
1956When you submit a query:
1957 
19581. The client gets the list of available tools from the server
19592. Your query is sent to Claude along with tool descriptions
19603. Claude decides which tools (if any) to use
19614. The client executes any requested tool calls through the server
19625. Results are sent back to Claude
19636. Claude provides a natural language response
19647. The response is displayed to you
1965 
1966## Best practices
1967 
19681. **Error Handling**
1969 * Wrap tool calls in `begin`...`rescue` blocks
1970 * Provide meaningful error messages
1971 * Gracefully handle connection issues
1972 
19732. **Resource Management**
1974 * Always close the transport when done
1975 * Use `begin`...`ensure` for proper cleanup
1976 * Handle server disconnections
1977 
19783. **Security**
1979 * Store API keys securely in `.env`
1980 * Validate server responses
1981 * Be cautious with tool permissions
1982 
19834. **Tool Names**
1984 * Tool names can be validated according to the format specified [here](/specification/2025-11-25/server/tools#tool-names)
1985 * If a tool name conforms to the specified format, it should not fail validation by an MCP client
1986 
1987## Troubleshooting
1988 
1989### Server Path Issues
1990 
1991* Double-check the path to your server script is correct
1992* Use the absolute path if the relative path isn't working
1993* For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
1994* Verify the server file has the correct extension (.py for Python, .js for Node.js, or .rb for Ruby)
1995 
1996Example of correct path usage:
1997 
1998```bash theme={null}
1999# Relative path
2000bundle exec ruby client.rb ./server/weather.rb
2001 
2002# Absolute path
2003bundle exec ruby client.rb /Users/username/projects/mcp-server/weather.rb
2004 
2005# Windows path (either format works)
2006bundle exec ruby client.rb C:/projects/mcp-server/weather.rb
2007bundle exec ruby client.rb C:\\projects\\mcp-server\\weather.rb
2008```
2009 
2010### Response Timing
2011 
2012* The first response might take up to 30 seconds to return
2013* This is normal and happens while:
2014 * The server initializes
2015 * Claude processes the query
2016 * Tools are being executed
2017* Subsequent responses are typically faster
2018* Don't interrupt the process during this initial waiting period
2019 
2020### Common Error Messages
2021 
2022If you see:
2023 
2024* `Errno::ENOENT`: Check your server path and ensure the command (`ruby`, `python3`, `node`) is available
2025* `Connection refused`: Ensure the server is running and the path is correct
2026* `Tool execution failed`: Verify the tool's required environment variables are set
2027* `Anthropic::Errors::AuthenticationError`: Check your `.env` file has a valid `ANTHROPIC_API_KEY`
2028 
2029**Rust**
2030 
2031[You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-rust)
2032 
2033## System Requirements
2034 
2035Before starting, ensure your Linux system meets these requirements:
2036 
2037* Latest stable version of [Rust and Cargo](https://www.rust-lang.org/tools/install)
2038* Anthropic API key (Claude)
2039* A Python, Node.js, or executable MCP server to connect to
2040 
2041## Setting Up Your Environment
2042 
2043First, create a new Rust project:
2044 
2045```bash theme={null}
2046cargo new mcp-client-rust
2047cd mcp-client-rust
2048```
2049 
2050Replace the contents of `Cargo.toml` with the following:
2051 
2052```toml Cargo.toml theme={null}
2053[package]
2054name = "mcp-client-rust"
2055version = "0.1.0"
2056edition = "2024"
2057 
2058[dependencies]
2059anyhow = "1.0.100"
2060genai = "0.4.2"
2061rmcp = { version = "0.8.0", features = ["server", "client", "transport-io", "transport-child-process"] }
2062tokio = { version = "1.47.1", features = ["full"] }
2063tracing = "0.1.41"
2064tracing-subscriber = { version = "0.3", features = ["env-filter"] }
2065serde_json = "1.0.128"
2066dotenvy = "0.15.7"
2067reqwest = "0.12.23"
2068```
2069 
2070The [`rmcp`](https://github.com/modelcontextprotocol/rust-sdk) crate provides the Rust MCP SDK and child-process transport. This example uses the [`genai`](https://github.com/jeremychone/rust-genai) crate to send requests to Claude and represent tools in the model request.
2071 
2072## Setting Up Your API Key
2073 
2074You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
2075 
2076Create a `.env` file to store it:
2077 
2078```bash theme={null}
2079echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env
2080```
2081 
2082Add `.env` to your `.gitignore`:
2083 
2084```bash theme={null}
2085echo ".env" >> .gitignore
2086```
2087 
2088> [!WARNING]
2089>
2090> Make sure you keep your `ANTHROPIC_API_KEY` secure!
2091 
2092## Creating the Client
2093 
2094Open `src/main.rs` and replace its contents as you work through the following sections.
2095 
2096### Imports and Client Structure
2097 
2098First, add the imports, model constant, and basic client structure:
2099 
2100```rust theme={null}
2101use anyhow::{Context, Result, bail};
2102use genai::Client;
2103use genai::chat::{
2104 ChatMessage, ChatRequest, ChatResponse, ContentPart, Tool as GenaiTool, ToolResponse,
2105};
2106use rmcp::model::{CallToolRequestParam, Tool as McpTool};
2107use rmcp::service::{RoleClient, RunningService, ServiceExt};
2108use rmcp::transport::TokioChildProcess;
2109use serde_json::Value;
2110use tokio::io::{self, AsyncBufReadExt, BufReader};
2111use tokio::process::Command;
2112 
2113const MODEL_ANTHROPIC: &str = "claude-sonnet-4-20250514";
2114 
2115struct MCPClient {
2116 anthropic: Client,
2117 session: Option<RunningService<RoleClient, ()>>,
2118 tools: Vec<GenaiTool>,
2119}
2120```
2121 
2122The client keeps the model API client, the active MCP session, and the tools advertised by the connected server.
2123 
2124### Client Initialization
2125 
2126Next, initialize the model client and start without an MCP session or tools:
2127 
2128```rust theme={null}
2129impl MCPClient {
2130 fn new() -> Result<Self> {
2131 Ok(MCPClient {
2132 anthropic: Client::default(),
2133 session: None,
2134 tools: Vec::new(),
2135 })
21312136 }
2132 ```
2133 
2134 The client keeps the model API client, the active MCP session, and the tools advertised by the connected server.
2135 
2136 ### Client Initialization
2137 
2138 Next, initialize the model client and start without an MCP session or tools:
2139 
2140 ```rust theme={null}
2141 impl MCPClient {
2142 fn new() -> Result<Self> {
2143 Ok(MCPClient {
2144 anthropic: Client::default(),
2145 session: None,
2146 tools: Vec::new(),
2147 })
2137 
2138 // Additional methods will go here.
2139}
2140```
2141 
2142`genai::Client::default()` reads the `ANTHROPIC_API_KEY` environment variable when it sends a request.
2143 
2144### Server Connection Management
2145 
2146Add this method inside the `impl MCPClient` block:
2147 
2148```rust theme={null}
2149async fn connect_to_server(&mut self, server_args: &[String]) -> Result<()> {
2150 if self.session.is_some() {
2151 bail!("Client is already connected to a server");
2152 }
2153 
2154 let mut command = Command::new(&server_args[0]);
2155 command.args(&server_args[1..]);
2156 
2157 let process = TokioChildProcess::new(command)
2158 .with_context(|| format!("Failed to spawn server process for {:?}", server_args))?;
2159 
2160 let session = ().serve(process).await?;
2161 
2162 let rmcp_tools = session
2163 .list_all_tools()
2164 .await
2165 .context("Unable to list tools from server")?;
2166 
2167 let tool_names: Vec<String> = rmcp_tools
2168 .iter()
2169 .map(|tool| tool.name.to_string())
2170 .collect();
2171 
2172 println!("Connected to server with tools: {tool_names:?}");
2173 
2174 self.tools = convert_tools(&rmcp_tools);
2175 self.session = Some(session);
2176 Ok(())
2177}
2178```
2179 
2180This method:
2181 
21821. Starts the server as a child process using the command and arguments supplied on the command line
21832. Establishes an MCP session over stdio
21843. Lists all tools advertised by the server
21854. Converts those tools into the format used in model requests
2186 
2187### Converting MCP Tools
2188 
2189Add this function outside the `impl MCPClient` block:
2190 
2191```rust theme={null}
2192fn convert_tools(tools: &[McpTool]) -> Vec<GenaiTool> {
2193 tools
2194 .iter()
2195 .map(|tool| GenaiTool {
2196 name: tool.name.to_string(),
2197 description: tool.description.as_deref().map(str::to_string),
2198 schema: Some(Value::Object(tool.input_schema.as_ref().clone())),
2199 config: None,
2200 })
2201 .collect()
2202}
2203```
2204 
2205MCP and model APIs describe tools with similar information but different Rust types. `convert_tools` maps each MCP tool's name, description, and input schema into a `genai` tool definition.
2206 
2207### Sending Model Requests
2208 
2209Add this helper method inside `impl MCPClient`:
2210 
2211```rust theme={null}
2212async fn request_model(&self, chat_req: &ChatRequest) -> Result<ChatResponse> {
2213 let response = self
2214 .anthropic
2215 .exec_chat(MODEL_ANTHROPIC, chat_req.clone(), None)
2216 .await
2217 .context("Anthropic chat request failed")?;
2218 
2219 Ok(response)
2220}
2221```
2222 
2223This keeps model request handling in one place and adds useful context if the API request fails.
2224 
2225### Query Processing Logic
2226 
2227Now add the core query-processing method inside `impl MCPClient`:
2228 
2229```rust theme={null}
2230async fn process_query(&mut self, query: &str) -> Result<String> {
2231 let session = self
2232 .session
2233 .as_ref()
2234 .context("Client is not connected to any server")?;
2235 
2236 let mut messages = vec![ChatMessage::user(query)];
2237 let mut final_text = Vec::new();
2238 
2239 // Initial Claude API call with tools
2240 let mut chat_req = ChatRequest::new(messages.clone()).with_tools(self.tools.clone());
2241 let mut chat_rsp = self.request_model(&chat_req).await?;
2242 
2243 // Process response content - collect text and handle tool calls
2244 for text in chat_rsp.texts() {
2245 final_text.push(text.to_string());
2246 }
2247 
2248 let tool_calls = chat_rsp.tool_calls();
2249 if !tool_calls.is_empty() {
2250 // Append assistant's response to message history
2251 messages.push(ChatMessage::assistant(chat_rsp.content.clone()));
2252 
2253 // Execute each tool call and collect responses
2254 let mut tool_results = Vec::new();
2255 for tool_call in tool_calls {
2256 // Add information about the tool call to final text
2257 let tool_args_str = serde_json::to_string(&tool_call.fn_arguments)
2258 .unwrap_or_else(|_| "{}".to_string());
2259 
2260 final_text.push(format!(
2261 "[Calling tool {} with args {}]",
2262 tool_call.fn_name, tool_args_str
2263 ));
2264 
2265 // Query the MCP server
2266 let tool_result = session
2267 .call_tool(CallToolRequestParam {
2268 name: tool_call.fn_name.clone().into(),
2269 arguments: tool_call.fn_arguments.as_object().cloned(),
2270 })
2271 .await
2272 .with_context(|| format!("Tool call {} failed", tool_call.fn_name))?;
2273 
2274 let payload = serde_json::to_string(&tool_result)
2275 .context("Failed to serialize tool result")?;
2276 
2277 tool_results.push(ContentPart::ToolResponse(ToolResponse::new(
2278 tool_call.call_id.clone(),
2279 payload,
2280 )));
21482281 }
21492282 
2150 // Additional methods will go here.
2151 }
2152 ```
2153 
2154 `genai::Client::default()` reads the `ANTHROPIC_API_KEY` environment variable when it sends a request.
2155 
2156 ### Server Connection Management
2157 
2158 Add this method inside the `impl MCPClient` block:
2159 
2160 ```rust theme={null}
2161 async fn connect_to_server(&mut self, server_args: &[String]) -> Result<()> {
2162 if self.session.is_some() {
2163 bail!("Client is already connected to a server");
2164 }
2165 
2166 let mut command = Command::new(&server_args[0]);
2167 command.args(&server_args[1..]);
2168 
2169 let process = TokioChildProcess::new(command)
2170 .with_context(|| format!("Failed to spawn server process for {:?}", server_args))?;
2171 
2172 let session = ().serve(process).await?;
2173 
2174 let rmcp_tools = session
2175 .list_all_tools()
2176 .await
2177 .context("Unable to list tools from server")?;
2178 
2179 let tool_names: Vec<String> = rmcp_tools
2180 .iter()
2181 .map(|tool| tool.name.to_string())
2182 .collect();
2183 
2184 println!("Connected to server with tools: {tool_names:?}");
2185 
2186 self.tools = convert_tools(&rmcp_tools);
2187 self.session = Some(session);
2188 Ok(())
2189 }
2190 ```
2191 
2192 This method:
2193 
2194 1. Starts the server as a child process using the command and arguments supplied on the command line
2195 2. Establishes an MCP session over stdio
2196 3. Lists all tools advertised by the server
2197 4. Converts those tools into the format used in model requests
2198 
2199 ### Converting MCP Tools
2200 
2201 Add this function outside the `impl MCPClient` block:
2202 
2203 ```rust theme={null}
2204 fn convert_tools(tools: &[McpTool]) -> Vec<GenaiTool> {
2205 tools
2206 .iter()
2207 .map(|tool| GenaiTool {
2208 name: tool.name.to_string(),
2209 description: tool.description.as_deref().map(str::to_string),
2210 schema: Some(Value::Object(tool.input_schema.as_ref().clone())),
2211 config: None,
2212 })
2213 .collect()
2214 }
2215 ```
2216 
2217 MCP and model APIs describe tools with similar information but different Rust types. `convert_tools` maps each MCP tool's name, description, and input schema into a `genai` tool definition.
2218 
2219 ### Sending Model Requests
2220 
2221 Add this helper method inside `impl MCPClient`:
2222 
2223 ```rust theme={null}
2224 async fn request_model(&self, chat_req: &ChatRequest) -> Result<ChatResponse> {
2225 let response = self
2226 .anthropic
2227 .exec_chat(MODEL_ANTHROPIC, chat_req.clone(), None)
2228 .await
2229 .context("Anthropic chat request failed")?;
2230 
2231 Ok(response)
2232 }
2233 ```
2234 
2235 This keeps model request handling in one place and adds useful context if the API request fails.
2236 
2237 ### Query Processing Logic
2238 
2239 Now add the core query-processing method inside `impl MCPClient`:
2240 
2241 ```rust theme={null}
2242 async fn process_query(&mut self, query: &str) -> Result<String> {
2243 let session = self
2244 .session
2245 .as_ref()
2246 .context("Client is not connected to any server")?;
2247 
2248 let mut messages = vec![ChatMessage::user(query)];
2249 let mut final_text = Vec::new();
2250 
2251 // Initial Claude API call with tools
2252 let mut chat_req = ChatRequest::new(messages.clone()).with_tools(self.tools.clone());
2253 let mut chat_rsp = self.request_model(&chat_req).await?;
2254 
2255 // Process response content - collect text and handle tool calls
2283 // Append tool responses to message history
2284 messages.push(ChatMessage::user(tool_results));
2285 
2286 // Build the next request and query model
2287 chat_req = ChatRequest::new(messages.clone());
2288 chat_rsp = self.request_model(&chat_req).await?;
2289 
2290 // Collect text from response
22562291 for text in chat_rsp.texts() {
22572292 final_text.push(text.to_string());
22582293 }
2259 
2260 let tool_calls = chat_rsp.tool_calls();
2261 if !tool_calls.is_empty() {
2262 // Append assistant's response to message history
2263 messages.push(ChatMessage::assistant(chat_rsp.content.clone()));
2264 
2265 // Execute each tool call and collect responses
2266 let mut tool_results = Vec::new();
2267 for tool_call in tool_calls {
2268 // Add information about the tool call to final text
2269 let tool_args_str = serde_json::to_string(&tool_call.fn_arguments)
2270 .unwrap_or_else(|_| "{}".to_string());
2271 
2272 final_text.push(format!(
2273 "[Calling tool {} with args {}]",
2274 tool_call.fn_name, tool_args_str
2275 ));
2276 
2277 // Query the MCP server
2278 let tool_result = session
2279 .call_tool(CallToolRequestParam {
2280 name: tool_call.fn_name.clone().into(),
2281 arguments: tool_call.fn_arguments.as_object().cloned(),
2282 })
2283 .await
2284 .with_context(|| format!("Tool call {} failed", tool_call.fn_name))?;
2285 
2286 let payload = serde_json::to_string(&tool_result)
2287 .context("Failed to serialize tool result")?;
2288 
2289 tool_results.push(ContentPart::ToolResponse(ToolResponse::new(
2290 tool_call.call_id.clone(),
2291 payload,
2292 )));
2293 }
2294 
2295 // Append tool responses to message history
2296 messages.push(ChatMessage::user(tool_results));
2297 
2298 // Build the next request and query model
2299 chat_req = ChatRequest::new(messages.clone());
2300 chat_rsp = self.request_model(&chat_req).await?;
2301 
2302 // Collect text from response
2303 for text in chat_rsp.texts() {
2304 final_text.push(text.to_string());
2305 }
2294 }
2295 
2296 Ok(final_text.join("\n"))
2297}
2298```
2299 
2300The method first sends the user's query and available tools to Claude. When Claude requests tools, the client executes each request through the MCP session, sends the results back to Claude, and collects the final text response.
2301 
2302### Interactive Chat Interface
2303 
2304Add the interactive terminal loop inside `impl MCPClient`:
2305 
2306```rust theme={null}
2307async fn chat_loop(&mut self) -> Result<()> {
2308 println!("\nMCP Client Started!");
2309 println!("Type your queries or 'quit' to exit.");
2310 
2311 let mut stdin = BufReader::new(io::stdin());
2312 let mut input = String::new();
2313 
2314 loop {
2315 print!("\nQuery: ");
2316 std::io::Write::flush(&mut std::io::stdout())?;
2317 
2318 input.clear();
2319 if stdin.read_line(&mut input).await? == 0 {
2320 break; // EOF
23062321 }
23072322 
2308 Ok(final_text.join("\n"))
2323 let query = input.trim();
2324 if query.eq_ignore_ascii_case("quit") {
2325 break;
2326 }
2327 if query.is_empty() {
2328 continue;
2329 }
2330 
2331 match self.process_query(query).await {
2332 Ok(response) => println!("\n{}", response),
2333 Err(err) => println!("\nError: {}", err),
2334 }
23092335 }
2310 ```
2311 
2312 The method first sends the user's query and available tools to Claude. When Claude requests tools, the client executes each request through the MCP session, sends the results back to Claude, and collects the final text response.
2313 
2314 ### Interactive Chat Interface
2315 
2316 Add the interactive terminal loop inside `impl MCPClient`:
2317 
2318 ```rust theme={null}
2319 async fn chat_loop(&mut self) -> Result<()> {
2320 println!("\nMCP Client Started!");
2321 println!("Type your queries or 'quit' to exit.");
2322 
2323 let mut stdin = BufReader::new(io::stdin());
2324 let mut input = String::new();
2325 
2326 loop {
2327 print!("\nQuery: ");
2328 std::io::Write::flush(&mut std::io::stdout())?;
2329 
2330 input.clear();
2331 if stdin.read_line(&mut input).await? == 0 {
2332 break; // EOF
2333 }
2334 
2335 let query = input.trim();
2336 if query.eq_ignore_ascii_case("quit") {
2337 break;
2338 }
2339 if query.is_empty() {
2340 continue;
2341 }
2342 
2343 match self.process_query(query).await {
2344 Ok(response) => println!("\n{}", response),
2345 Err(err) => println!("\nError: {}", err),
2346 }
2347 }
2348 
2349 Ok(())
2336 
2337 Ok(())
2338}
2339```
2340 
2341The loop accepts queries until the user types `quit` or closes standard input. Query errors are printed without terminating the client.
2342 
2343### Cleanup
2344 
2345Add this method inside `impl MCPClient` to stop the MCP session and child process:
2346 
2347```rust theme={null}
2348async fn cleanup(&mut self) -> Result<()> {
2349 if let Some(session) = self.session.take() {
2350 let _ = session.cancel().await;
23502351 }
2351 ```
2352 
2353 The loop accepts queries until the user types `quit` or closes standard input. Query errors are printed without terminating the client.
2354 
2355 ### Cleanup
2356 
2357 Add this method inside `impl MCPClient` to stop the MCP session and child process:
2358 
2359 ```rust theme={null}
2360 async fn cleanup(&mut self) -> Result<()> {
2361 if let Some(session) = self.session.take() {
2362 let _ = session.cancel().await;
2363 }
2364 Ok(())
2352 Ok(())
2353}
2354```
2355 
2356### Main Entry Point
2357 
2358Finally, add the asynchronous entry point outside the `impl MCPClient` block:
2359 
2360```rust theme={null}
2361#[tokio::main]
2362async fn main() -> Result<()> {
2363 dotenvy::dotenv().context("Failed to load env file")?;
2364 
2365 let mut args = std::env::args();
2366 let _ = args.next();
2367 let server_args: Vec<String> = args.collect();
2368 
2369 if server_args.is_empty() {
2370 eprintln!("Usage: cargo run -- <server_script_or_binary> [args...]");
2371 std::process::exit(1);
23652372 }
2366 ```
2367 
2368 ### Main Entry Point
2369 
2370 Finally, add the asynchronous entry point outside the `impl MCPClient` block:
2371 
2372 ```rust theme={null}
2373 #[tokio::main]
2374 async fn main() -> Result<()> {
2375 dotenvy::dotenv().context("Failed to load env file")?;
2376 
2377 let mut args = std::env::args();
2378 let _ = args.next();
2379 let server_args: Vec<String> = args.collect();
2380 
2381 if server_args.is_empty() {
2382 eprintln!("Usage: cargo run -- <server_script_or_binary> [args...]");
2383 std::process::exit(1);
2384 }
2385 
2386 let mut client = MCPClient::new()?;
2387 
2388 let result = async {
2389 client.connect_to_server(&server_args).await?;
2390 client.chat_loop().await
2391 }
2392 .await;
2393 
2394 let cleanup_result = client.cleanup().await;
2395 
2396 result?;
2397 cleanup_result?;
2398 
2399 Ok(())
2373 
2374 let mut client = MCPClient::new()?;
2375 
2376 let result = async {
2377 client.connect_to_server(&server_args).await?;
2378 client.chat_loop().await
24002379 }
2401 ```
2402 
2403 The entry point loads `.env`, treats all remaining command-line arguments as the server command, connects the client, starts the chat loop, and ensures cleanup runs before exiting.
2404 
2405 ### Verify the Complete File
2406 
2407 Before running the client, confirm the items in `src/main.rs` are placed at the correct scope:
2408 
2409 * `new`, `connect_to_server`, `process_query`, `request_model`, `chat_loop`, and `cleanup` are methods inside the single `impl MCPClient` block.
2410 * `main` and `convert_tools` are functions outside the `impl MCPClient` block.
2411 
2412 Rust does not require these items to appear in a particular order, but methods and free functions must be placed in the correct scope. Compare your file with the [complete `src/main.rs` example](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-rust/src/main.rs), then check that it compiles:
2413 
2414 ```bash theme={null}
2415 cargo fmt --check
2416 cargo check
2417 ```
2418 
2419 ## Running the Client
2420 
2421 Use `cargo run --` followed by the command you would normally use to start the MCP server:
2422 
2423 ```bash theme={null}
2424 # Python server
2425 cargo run -- python path/to/server.py
2426 
2427 # Node.js server
2428 cargo run -- node path/to/build/index.js
2429 
2430 # Executable server
2431 cargo run -- path/to/server-binary
2432 ```
2433 
2434 Running bare `cargo run` without a server command prints the usage message and exits.
2435 
2436 <Note>
2437 If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-rust), build the server first and then run a command similar to: `cargo run -- ../weather-server-rust/target/debug/weather`
2438 </Note>
2439 
2440 The client will:
2441 
2442 1. Start and connect to the specified MCP server
2443 2. List the tools available from that server
2444 3. Start an interactive chat session where you can:
2445 * Enter queries
2446 * See tool executions
2447 * Get responses from Claude
2448 
2449 ## How It Works
2450 
2451 When you submit a query:
2452 
2453 1. The client sends your query and the server's available tools to Claude
2454 2. Claude decides which tools, if any, to use
2455 3. The client executes requested tools through the MCP session
2456 4. Tool results are sent back to Claude
2457 5. Claude provides a natural language response
2458 6. The response is displayed in the terminal
2459 
2460 ## Best Practices
2461 
2462 1. **Error Handling**
2463 * Add context to errors at process, MCP, model API, and serialization boundaries
2464 * Report individual query errors without terminating the interactive session
2465 * Validate server commands before running them
2466 
2467 2. **Resource Management**
2468 * Always cancel the MCP session during cleanup
2469 * Ensure cleanup runs even when connection or chat-loop operations fail
2470 * Avoid starting a second server while a session is active
2471 
2472 3. **Security**
2473 * Store API keys securely in `.env`
2474 * Review the tools exposed by a server before allowing model-driven calls
2475 * Connect only to servers and executable commands you trust
2476 
2477 ## Troubleshooting
2478 
2479 ### Server Command Issues
2480 
2481 The arguments after `cargo run --` must form a complete command. Interpreted server scripts need their runtime:
2482 
2483 ```bash theme={null}
2484 # Correct
2485 cargo run -- python ./server/weather.py
2486 cargo run -- node ./server/build/index.js
2487 
2488 # Incorrect: a Python script is not necessarily executable by itself
2489 cargo run -- ./server/weather.py
2490 ```
2491 
2492 If a command cannot be found, use its absolute path or verify it is available in your `PATH`.
2493 
2494 ### Environment File Issues
2495 
2496 If you see `Failed to load env file`, ensure `.env` exists in the directory where you run the client.
2497 
2498 If the model request reports a missing API key, confirm that `.env` contains:
2499 
2500 ```text theme={null}
2501 ANTHROPIC_API_KEY=your-api-key-goes-here
2502 ```
2503 
2504 ### Tool and Response Errors
2505 
2506 * `Unable to list tools from server`: Verify the server starts successfully and communicates over stdio
2507 * `Tool call ... failed`: Verify the server tool's required arguments and environment variables
2508 * `Failed to serialize tool result`: Inspect the server's response for unsupported or malformed content
2509 </Tab>
2510</Tabs>
2380 .await;
2381 
2382 let cleanup_result = client.cleanup().await;
2383 
2384 result?;
2385 cleanup_result?;
2386 
2387 Ok(())
2388}
2389```
2390 
2391The entry point loads `.env`, treats all remaining command-line arguments as the server command, connects the client, starts the chat loop, and ensures cleanup runs before exiting.
2392 
2393### Verify the Complete File
2394 
2395Before running the client, confirm the items in `src/main.rs` are placed at the correct scope:
2396 
2397* `new`, `connect_to_server`, `process_query`, `request_model`, `chat_loop`, and `cleanup` are methods inside the single `impl MCPClient` block.
2398* `main` and `convert_tools` are functions outside the `impl MCPClient` block.
2399 
2400Rust does not require these items to appear in a particular order, but methods and free functions must be placed in the correct scope. Compare your file with the [complete `src/main.rs` example](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-rust/src/main.rs), then check that it compiles:
2401 
2402```bash theme={null}
2403cargo fmt --check
2404cargo check
2405```
2406 
2407## Running the Client
2408 
2409Use `cargo run --` followed by the command you would normally use to start the MCP server:
2410 
2411```bash theme={null}
2412# Python server
2413cargo run -- python path/to/server.py
2414 
2415# Node.js server
2416cargo run -- node path/to/build/index.js
2417 
2418# Executable server
2419cargo run -- path/to/server-binary
2420```
2421 
2422Running bare `cargo run` without a server command prints the usage message and exits.
2423 
2424> [!NOTE]
2425>
2426> If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-rust), build the server first and then run a command similar to: `cargo run -- ../weather-server-rust/target/debug/weather`
2427 
2428The client will:
2429 
24301. Start and connect to the specified MCP server
24312. List the tools available from that server
24323. Start an interactive chat session where you can:
2433 * Enter queries
2434 * See tool executions
2435 * Get responses from Claude
2436 
2437## How It Works
2438 
2439When you submit a query:
2440 
24411. The client sends your query and the server's available tools to Claude
24422. Claude decides which tools, if any, to use
24433. The client executes requested tools through the MCP session
24444. Tool results are sent back to Claude
24455. Claude provides a natural language response
24466. The response is displayed in the terminal
2447 
2448## Best Practices
2449 
24501. **Error Handling**
2451 * Add context to errors at process, MCP, model API, and serialization boundaries
2452 * Report individual query errors without terminating the interactive session
2453 * Validate server commands before running them
2454 
24552. **Resource Management**
2456 * Always cancel the MCP session during cleanup
2457 * Ensure cleanup runs even when connection or chat-loop operations fail
2458 * Avoid starting a second server while a session is active
2459 
24603. **Security**
2461 * Store API keys securely in `.env`
2462 * Review the tools exposed by a server before allowing model-driven calls
2463 * Connect only to servers and executable commands you trust
2464 
2465## Troubleshooting
2466 
2467### Server Command Issues
2468 
2469The arguments after `cargo run --` must form a complete command. Interpreted server scripts need their runtime:
2470 
2471```bash theme={null}
2472# Correct
2473cargo run -- python ./server/weather.py
2474cargo run -- node ./server/build/index.js
2475 
2476# Incorrect: a Python script is not necessarily executable by itself
2477cargo run -- ./server/weather.py
2478```
2479 
2480If a command cannot be found, use its absolute path or verify it is available in your `PATH`.
2481 
2482### Environment File Issues
2483 
2484If you see `Failed to load env file`, ensure `.env` exists in the directory where you run the client.
2485 
2486If the model request reports a missing API key, confirm that `.env` contains:
2487 
2488```text theme={null}
2489ANTHROPIC_API_KEY=your-api-key-goes-here
2490```
2491 
2492### Tool and Response Errors
2493 
2494* `Unable to list tools from server`: Verify the server starts successfully and communicates over stdio
2495* `Tool call ... failed`: Verify the server tool's required arguments and environment variables
2496* `Failed to serialize tool result`: Inspect the server's response for unsupported or malformed content
25112497 
25122498## Next steps
25132499 
2514<CardGroup cols={2}>
2515 <Card title="Example servers" icon="grid" href="/examples">
2516 Check out our gallery of official MCP servers and implementations
2517 </Card>
2518</CardGroup>
2500> **[Example servers](/examples)**
2501>
2502> Check out our gallery of official MCP servers and implementations
25192503 

docs/2025-11-25/develop/build-server Changed · +2869 / -2937 lines

### Prerequisite knowledge ### Logging in MCP Servers ### Best Practices ### Quick Examples ### System requirements ### Set up your environment ## Building your server ### Importing packages and setting up the instance ### Helper functions ### Implementing tool execution ### Running the server ## Testing your server with Claude for Desktop ### Prerequisite knowledge ### Logging in MCP Servers ### Best Practices ### Quick Examples ### System requirements ### Set up your environment ## Building your server ### Importing packages and setting up the instance ### Helper functions ### Implementing tool execution ### Running the server ## Testing your server with Claude for Desktop ### Logging in MCP Servers ### Best Practices ### System requirements ### Set up your environment ## Building your server ### Weather Service ### Create your Boot Application ### Running the server ## Testing your server with Claude for Desktop ## Testing your server with Java client ### Create an MCP Client manually ### Use MCP Client Boot Starter ## More Java MCP Server examples ### Prerequisite knowledge ### Logging in MCP Servers ### Best Practices ### System requirements ### Set up your environment ## Building your server ### Setting up the instance ### Weather API helper functions ### Implementing tool execution ### Running the server ## Testing your server with Claude for Desktop ### Prerequisite knowledge ### Logging in MCP Servers ### Best Practices ### System requirements ### Set up your environment ## Building your server ### Weather API helper functions ### Running the server ## Testing your server with Claude for Desktop ### Prerequisite knowledge ### Logging in MCP Servers ### Best Practices ### Quick Examples ### System requirements ### Set up your environment ## Building your server ### Importing packages and setting up constants ### Helper methods ### Implementing tool execution ### Running the server ## Testing your server with Claude for Desktop ### Prerequisite knowledge ### Logging in MCP Servers ### Best Practices ### Quick Examples ### System requirements ### Set up your environment ## Building your server ### Importing packages and constants ### Data structures ### Helper functions ### Implementing the Weather server and tools ### Implementing the ServerHandler ### Running the server ## Testing your server with Claude for Desktop ### Prerequisite knowledge ### Logging in MCP Servers ### Best Practices ### Quick Examples ### System requirements ### Set up your environment ## Building your server ### Importing packages and constants ### Data structures ### Helper functions ### Implementing tool execution ### Running the server ## Testing your server with Claude for Desktop

The two sides of this change are more than 400 edits apart, too far apart to line up, so this is the differ's own diff of it and the words inside a line are not marked.

from line 8
88 
99We'll build a server that exposes two tools: `get_alerts` and `get_forecast`. Then we'll connect the server to an MCP host (in this case, Claude for Desktop):
1010 
11<Frame>
12 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/current-weather.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=dce7b2f8a06c20ba358e4bd2e75fa4c7" width="2780" height="1849" data-path="images/current-weather.png" />
13</Frame>
14 
15<Note>
16 Servers can connect to any client. We've chosen Claude for Desktop here for simplicity, but we also have a guide on [building your own client](/docs/2025-11-25/develop/build-client).
17</Note>
11![](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/current-weather.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=dce7b2f8a06c20ba358e4bd2e75fa4c7)
12 
13> [!NOTE]
14>
15> Servers can connect to any client. We've chosen Claude for Desktop here for simplicity, but we also have a guide on [building your own client](/docs/2025-11-25/develop/build-client).
1816 
1917### Core MCP Concepts
2018 
from line 24
2624 
2725This tutorial will primarily focus on tools.
2826 
29<Tabs>
30 <Tab title="Python">
31 Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python)
32 
33 ### Prerequisite knowledge
34 
35 This quickstart assumes you have familiarity with:
36 
37 * Python
38 * LLMs like Claude
39 
40 ### Logging in MCP Servers
41 
42 When implementing MCP servers, be careful about how you handle logging:
43 
44 **For STDIO-based servers:** Never write to stdout. Writing to stdout will corrupt the JSON-RPC messages and break your server. The `print()` function writes to stdout by default, but can be used safely with `file=sys.stderr`.
45 
46 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
47 
48 ### Best Practices
49 
50 * Use a logging library that writes to stderr or files.
51 
52 ### Quick Examples
53 
54 ```python theme={null}
55 import sys
56 import logging
57 
58 # ❌ Bad (STDIO)
59 print("Processing request")
60 
61 # ✅ Good (STDIO)
62 print("Processing request", file=sys.stderr)
63 
64 # ✅ Good (STDIO)
65 logging.info("Processing request")
66 ```
67 
68 ### System requirements
69 
70 * Python 3.10 or higher installed.
71 * You must use the Python MCP SDK 1.2.0 or higher.
72 
73 ### Set up your environment
74 
75 First, let's install `uv` and set up our Python project and environment:
76 
77 <CodeGroup>
78 ```bash macOS/Linux theme={null}
79 curl -LsSf https://astral.sh/uv/install.sh | sh
80 ```
81 
82 ```powershell Windows theme={null}
83 powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
84 ```
85 </CodeGroup>
86 
87 Make sure to restart your terminal afterwards to ensure that the `uv` command gets picked up.
88 
89 Now, let's create and set up our project:
90 
91 <CodeGroup>
92 ```bash macOS/Linux theme={null}
93 # Create a new directory for our project
94 uv init weather
95 cd weather
96 
97 # Create virtual environment and activate it
98 uv venv
99 source .venv/bin/activate
100 
101 # Install dependencies
102 uv add "mcp[cli]" httpx
103 
104 # Create our server file
105 touch weather.py
106 ```
107 
108 ```powershell Windows theme={null}
109 # Create a new directory for our project
110 uv init weather
111 cd weather
112 
113 # Create virtual environment and activate it
114 uv venv
115 .venv\Scripts\activate
116 
117 # Install dependencies
118 uv add mcp[cli] httpx
119 
120 # Create our server file
121 new-item weather.py
122 ```
123 </CodeGroup>
124 
125 Now let's dive into building your server.
126 
127 ## Building your server
128 
129 ### Importing packages and setting up the instance
130 
131 Add these to the top of your `weather.py`:
132 
133 ```python theme={null}
134 from typing import Any
135 
136 import httpx
137 from mcp.server.fastmcp import FastMCP
138 
139 # Initialize FastMCP server
140 mcp = FastMCP("weather")
141 
142 # Constants
143 NWS_API_BASE = "https://api.weather.gov"
144 USER_AGENT = "weather-app/1.0"
145 ```
146 
147 The FastMCP class uses Python type hints and docstrings to automatically generate tool definitions, making it easy to create and maintain MCP tools.
148 
149 ### Helper functions
150 
151 Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
152 
153 ```python theme={null}
154 async def make_nws_request(url: str) -> dict[str, Any] | None:
155 """Make a request to the NWS API with proper error handling."""
156 headers = {"User-Agent": USER_AGENT, "Accept": "application/geo+json"}
157 async with httpx.AsyncClient() as client:
158 try:
159 response = await client.get(url, headers=headers, timeout=30.0)
160 response.raise_for_status()
161 return response.json()
162 except Exception:
163 return None
164 
165 
166 def format_alert(feature: dict) -> str:
167 """Format an alert feature into a readable string."""
168 props = feature["properties"]
169 return f"""
170 Event: {props.get("event", "Unknown")}
171 Area: {props.get("areaDesc", "Unknown")}
172 Severity: {props.get("severity", "Unknown")}
173 Description: {props.get("description", "No description available")}
174 Instructions: {props.get("instruction", "No specific instructions provided")}
27**Python**
28 
29Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python)
30 
31### Prerequisite knowledge
32 
33This quickstart assumes you have familiarity with:
34 
35* Python
36* LLMs like Claude
37 
38### Logging in MCP Servers
39 
40When implementing MCP servers, be careful about how you handle logging:
41 
42**For STDIO-based servers:** Never write to stdout. Writing to stdout will corrupt the JSON-RPC messages and break your server. The `print()` function writes to stdout by default, but can be used safely with `file=sys.stderr`.
43 
44**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
45 
46### Best Practices
47 
48* Use a logging library that writes to stderr or files.
49 
50### Quick Examples
51 
52```python theme={null}
53import sys
54import logging
55 
56# ❌ Bad (STDIO)
57print("Processing request")
58 
59# ✅ Good (STDIO)
60print("Processing request", file=sys.stderr)
61 
62# ✅ Good (STDIO)
63logging.info("Processing request")
64```
65 
66### System requirements
67 
68* Python 3.10 or higher installed.
69* You must use the Python MCP SDK 1.2.0 or higher.
70 
71### Set up your environment
72 
73First, let's install `uv` and set up our Python project and environment:
74 
75```bash macOS/Linux theme={null}
76curl -LsSf https://astral.sh/uv/install.sh | sh
77```
78 
79```powershell Windows theme={null}
80powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
81```
82 
83Make sure to restart your terminal afterwards to ensure that the `uv` command gets picked up.
84 
85Now, let's create and set up our project:
86 
87```bash macOS/Linux theme={null}
88# Create a new directory for our project
89uv init weather
90cd weather
91 
92# Create virtual environment and activate it
93uv venv
94source .venv/bin/activate
95 
96# Install dependencies
97uv add "mcp[cli]" httpx
98 
99# Create our server file
100touch weather.py
101```
102 
103```powershell Windows theme={null}
104# Create a new directory for our project
105uv init weather
106cd weather
107 
108# Create virtual environment and activate it
109uv venv
110.venv\Scripts\activate
111 
112# Install dependencies
113uv add mcp[cli] httpx
114 
115# Create our server file
116new-item weather.py
117```
118 
119Now let's dive into building your server.
120 
121## Building your server
122 
123### Importing packages and setting up the instance
124 
125Add these to the top of your `weather.py`:
126 
127```python theme={null}
128from typing import Any
129 
130import httpx
131from mcp.server.fastmcp import FastMCP
132 
133# Initialize FastMCP server
134mcp = FastMCP("weather")
135 
136# Constants
137NWS_API_BASE = "https://api.weather.gov"
138USER_AGENT = "weather-app/1.0"
139```
140 
141The FastMCP class uses Python type hints and docstrings to automatically generate tool definitions, making it easy to create and maintain MCP tools.
142 
143### Helper functions
144 
145Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
146 
147```python theme={null}
148async def make_nws_request(url: str) -> dict[str, Any] | None:
149 """Make a request to the NWS API with proper error handling."""
150 headers = {"User-Agent": USER_AGENT, "Accept": "application/geo+json"}
151 async with httpx.AsyncClient() as client:
152 try:
153 response = await client.get(url, headers=headers, timeout=30.0)
154 response.raise_for_status()
155 return response.json()
156 except Exception:
157 return None
158 
159 
160def format_alert(feature: dict) -> str:
161 """Format an alert feature into a readable string."""
162 props = feature["properties"]
163 return f"""
164Event: {props.get("event", "Unknown")}
165Area: {props.get("areaDesc", "Unknown")}
166Severity: {props.get("severity", "Unknown")}
167Description: {props.get("description", "No description available")}
168Instructions: {props.get("instruction", "No specific instructions provided")}
169"""
170```
171 
172### Implementing tool execution
173 
174The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
175 
176```python theme={null}
177@mcp.tool()
178async def get_alerts(state: str) -> str:
179 """Get weather alerts for a US state.
180 
181 Args:
182 state: Two-letter US state code (e.g. CA, NY)
175183 """
176 ```
177 
178 ### Implementing tool execution
179 
180 The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
181 
182 ```python theme={null}
183 @mcp.tool()
184 async def get_alerts(state: str) -> str:
185 """Get weather alerts for a US state.
186 
187 Args:
188 state: Two-letter US state code (e.g. CA, NY)
184 url = f"{NWS_API_BASE}/alerts/active/area/{state}"
185 data = await make_nws_request(url)
186 
187 if not data or "features" not in data:
188 return "Unable to fetch alerts or no alerts found."
189 
190 if not data["features"]:
191 return "No active alerts for this state."
192 
193 alerts = [format_alert(feature) for feature in data["features"]]
194 return "\n---\n".join(alerts)
195 
196 
197@mcp.tool()
198async def get_forecast(latitude: float, longitude: float) -> str:
199 """Get weather forecast for a location.
200 
201 Args:
202 latitude: Latitude of the location
203 longitude: Longitude of the location
204 """
205 # First get the forecast grid endpoint
206 points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
207 points_data = await make_nws_request(points_url)
208 
209 if not points_data:
210 return "Unable to fetch forecast data for this location."
211 
212 # Get the forecast URL from the points response
213 forecast_url = points_data["properties"]["forecast"]
214 forecast_data = await make_nws_request(forecast_url)
215 
216 if not forecast_data:
217 return "Unable to fetch detailed forecast."
218 
219 # Format the periods into a readable forecast
220 periods = forecast_data["properties"]["periods"]
221 forecasts = []
222 for period in periods[:5]: # Only show next 5 periods
223 forecast = f"""
224{period["name"]}:
225Temperature: {period["temperature"]}°{period["temperatureUnit"]}
226Wind: {period["windSpeed"]} {period["windDirection"]}
227Forecast: {period["detailedForecast"]}
228"""
229 forecasts.append(forecast)
230 
231 return "\n---\n".join(forecasts)
232```
233 
234### Running the server
235 
236Finally, let's initialize and run the server:
237 
238```python theme={null}
239def main():
240 # Initialize and run the server
241 mcp.run(transport="stdio")
242 
243 
244if __name__ == "__main__":
245 main()
246```
247 
248Your server is complete! Run `uv run weather.py` to start the MCP server, which will listen for messages from MCP hosts.
249 
250Let's now test your server from an existing MCP host, Claude for Desktop.
251 
252## Testing your server with Claude for Desktop
253 
254> [!NOTE]
255>
256> Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/docs/2025-11-25/develop/build-client) tutorial to build an MCP client that connects to the server we just built.
257 
258First, make sure you have Claude for Desktop installed. [You can install the latest version
259here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
260 
261We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
262 
263For example, if you have [VS Code](https://code.visualstudio.com/) installed:
264 
265```bash macOS/Linux theme={null}
266code ~/Library/Application\ Support/Claude/claude_desktop_config.json
267```
268 
269```powershell Windows theme={null}
270code $env:AppData\Claude\claude_desktop_config.json
271```
272 
273You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
274 
275In this case, we'll add our single weather server like so:
276 
277```json macOS/Linux theme={null}
278{
279 "mcpServers": {
280 "weather": {
281 "command": "uv",
282 "args": [
283 "--directory",
284 "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
285 "run",
286 "weather.py"
287 ]
288 }
289 }
290}
291```
292 
293```json Windows theme={null}
294{
295 "mcpServers": {
296 "weather": {
297 "command": "uv",
298 "args": [
299 "--directory",
300 "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather",
301 "run",
302 "weather.py"
303 ]
304 }
305 }
306}
307```
308 
309> [!WARNING]
310>
311> You may need to put the full path to the `uv` executable in the `command` field. You can get this by running `which uv` on macOS/Linux or `where uv` on Windows.
312 
313> [!NOTE]
314>
315> Make sure you pass in the absolute path to your server. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path.
316 
317This tells Claude for Desktop:
318 
3191. There's an MCP server named "weather"
3202. To launch it by running `uv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather.py`
321 
322Save the file, and restart **Claude for Desktop**.
323 
324**TypeScript**
325 
326Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript)
327 
328### Prerequisite knowledge
329 
330This quickstart assumes you have familiarity with:
331 
332* TypeScript
333* LLMs like Claude
334 
335### Logging in MCP Servers
336 
337When implementing MCP servers, be careful about how you handle logging:
338 
339**For STDIO-based servers:** Never use `console.log()`, as it writes to standard output (stdout) by default. Writing to stdout will corrupt the JSON-RPC messages and break your server.
340 
341**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
342 
343### Best Practices
344 
345* Use `console.error()` which writes to stderr, or use a logging library that writes to stderr or files.
346 
347### Quick Examples
348 
349```javascript theme={null}
350// ❌ Bad (STDIO)
351console.log("Server started");
352 
353// ✅ Good (STDIO)
354console.error("Server started"); // stderr is safe
355```
356 
357### System requirements
358 
359For TypeScript, make sure you have the latest version of Node installed.
360 
361### Set up your environment
362 
363First, let's install Node.js and npm if you haven't already. You can download them from [nodejs.org](https://nodejs.org/).
364Verify your Node.js installation:
365 
366```bash theme={null}
367node --version
368npm --version
369```
370 
371For this tutorial, you'll need Node.js version 16 or higher.
372 
373Now, let's create and set up our project:
374 
375```bash macOS/Linux theme={null}
376# Create a new directory for our project
377mkdir weather
378cd weather
379 
380# Initialize a new npm project
381npm init -y
382 
383# Install dependencies
384npm install @modelcontextprotocol/sdk zod@3
385npm install -D @types/node typescript
386 
387# Create our files
388mkdir src
389touch src/index.ts
390```
391 
392```powershell Windows theme={null}
393# Create a new directory for our project
394md weather
395cd weather
396 
397# Initialize a new npm project
398npm init -y
399 
400# Install dependencies
401npm install @modelcontextprotocol/sdk zod@3
402npm install -D @types/node typescript
403 
404# Create our files
405md src
406new-item src\index.ts
407```
408 
409Update your package.json to add type: "module" and a build script:
410 
411```json package.json theme={null}
412{
413 "type": "module",
414 "bin": {
415 "weather": "./build/index.js"
416 },
417 "scripts": {
418 "build": "tsc && chmod 755 build/index.js"
419 },
420 "files": ["build"]
421}
422```
423 
424Create a `tsconfig.json` in the root of your project:
425 
426```json tsconfig.json theme={null}
427{
428 "compilerOptions": {
429 "target": "ES2022",
430 "module": "Node16",
431 "moduleResolution": "Node16",
432 "outDir": "./build",
433 "rootDir": "./src",
434 "strict": true,
435 "esModuleInterop": true,
436 "skipLibCheck": true,
437 "forceConsistentCasingInFileNames": true
438 },
439 "include": ["src/**/*"],
440 "exclude": ["node_modules"]
441}
442```
443 
444Now let's dive into building your server.
445 
446## Building your server
447 
448### Importing packages and setting up the instance
449 
450Add these to the top of your `src/index.ts`:
451 
452```typescript theme={null}
453import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
454import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
455import { z } from "zod";
456 
457const NWS_API_BASE = "https://api.weather.gov";
458const USER_AGENT = "weather-app/1.0";
459 
460// Create server instance
461const server = new McpServer({
462 name: "weather",
463 version: "1.0.0",
464});
465```
466 
467### Helper functions
468 
469Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
470 
471```typescript theme={null}
472// Helper function for making NWS API requests
473async function makeNWSRequest<T>(url: string): Promise<T | null> {
474 const headers = {
475 "User-Agent": USER_AGENT,
476 Accept: "application/geo+json",
477 };
478 
479 try {
480 const response = await fetch(url, { headers });
481 if (!response.ok) {
482 throw new Error(`HTTP error! status: ${response.status}`);
483 }
484 return (await response.json()) as T;
485 } catch (error) {
486 console.error("Error making NWS request:", error);
487 return null;
488 }
489}
490 
491interface AlertFeature {
492 properties: {
493 event?: string;
494 areaDesc?: string;
495 severity?: string;
496 status?: string;
497 headline?: string;
498 };
499}
500 
501// Format alert data
502function formatAlert(feature: AlertFeature): string {
503 const props = feature.properties;
504 return [
505 `Event: ${props.event || "Unknown"}`,
506 `Area: ${props.areaDesc || "Unknown"}`,
507 `Severity: ${props.severity || "Unknown"}`,
508 `Status: ${props.status || "Unknown"}`,
509 `Headline: ${props.headline || "No headline"}`,
510 "---",
511 ].join("\n");
512}
513 
514interface ForecastPeriod {
515 name?: string;
516 temperature?: number;
517 temperatureUnit?: string;
518 windSpeed?: string;
519 windDirection?: string;
520 shortForecast?: string;
521}
522 
523interface AlertsResponse {
524 features: AlertFeature[];
525}
526 
527interface PointsResponse {
528 properties: {
529 forecast?: string;
530 };
531}
532 
533interface ForecastResponse {
534 properties: {
535 periods: ForecastPeriod[];
536 };
537}
538```
539 
540### Implementing tool execution
541 
542The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
543 
544```typescript theme={null}
545// Register weather tools
546 
547server.registerTool(
548 "get_alerts",
549 {
550 description: "Get weather alerts for a state",
551 inputSchema: {
552 state: z
553 .string()
554 .length(2)
555 .describe("Two-letter state code (e.g. CA, NY)"),
556 },
557 },
558 async ({ state }) => {
559 const stateCode = state.toUpperCase();
560 const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`;
561 const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl);
562 
563 if (!alertsData) {
564 return {
565 content: [
566 {
567 type: "text",
568 text: "Failed to retrieve alerts data",
569 },
570 ],
571 };
572 }
573 
574 const features = alertsData.features || [];
575 if (!features.length) {
576 return {
577 content: [
578 {
579 type: "text",
580 text: `No active alerts for ${stateCode}`,
581 },
582 ],
583 };
584 }
585 
586 const formattedAlerts = features.map(formatAlert);
587 const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join("\n")}`;
588 
589 return {
590 content: [
591 {
592 type: "text",
593 text: alertsText,
594 },
595 ],
596 };
597 },
598);
599 
600server.registerTool(
601 "get_forecast",
602 {
603 description: "Get weather forecast for a location",
604 inputSchema: {
605 latitude: z
606 .number()
607 .min(-90)
608 .max(90)
609 .describe("Latitude of the location"),
610 longitude: z
611 .number()
612 .min(-180)
613 .max(180)
614 .describe("Longitude of the location"),
615 },
616 },
617 async ({ latitude, longitude }) => {
618 // Get grid point data
619 const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`;
620 const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl);
621 
622 if (!pointsData) {
623 return {
624 content: [
625 {
626 type: "text",
627 text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`,
628 },
629 ],
630 };
631 }
632 
633 const forecastUrl = pointsData.properties?.forecast;
634 if (!forecastUrl) {
635 return {
636 content: [
637 {
638 type: "text",
639 text: "Failed to get forecast URL from grid point data",
640 },
641 ],
642 };
643 }
644 
645 // Get forecast data
646 const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl);
647 if (!forecastData) {
648 return {
649 content: [
650 {
651 type: "text",
652 text: "Failed to retrieve forecast data",
653 },
654 ],
655 };
656 }
657 
658 const periods = forecastData.properties?.periods || [];
659 if (periods.length === 0) {
660 return {
661 content: [
662 {
663 type: "text",
664 text: "No forecast periods available",
665 },
666 ],
667 };
668 }
669 
670 // Format forecast periods
671 const formattedForecast = periods.map((period: ForecastPeriod) =>
672 [
673 `${period.name || "Unknown"}:`,
674 `Temperature: ${period.temperature || "Unknown"}°${period.temperatureUnit || "F"}`,
675 `Wind: ${period.windSpeed || "Unknown"} ${period.windDirection || ""}`,
676 `${period.shortForecast || "No forecast available"}`,
677 "---",
678 ].join("\n"),
679 );
680 
681 const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join("\n")}`;
682 
683 return {
684 content: [
685 {
686 type: "text",
687 text: forecastText,
688 },
689 ],
690 };
691 },
692);
693```
694 
695### Running the server
696 
697Finally, implement the main function to run the server:
698 
699```typescript theme={null}
700async function main() {
701 const transport = new StdioServerTransport();
702 await server.connect(transport);
703 console.error("Weather MCP Server running on stdio");
704}
705 
706main().catch((error) => {
707 console.error("Fatal error in main():", error);
708 process.exit(1);
709});
710```
711 
712Make sure to run `npm run build` to build your server! This is a very important step in getting your server to connect.
713 
714Let's now test your server from an existing MCP host, Claude for Desktop.
715 
716## Testing your server with Claude for Desktop
717 
718> [!NOTE]
719>
720> Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/docs/2025-11-25/develop/build-client) tutorial to build an MCP client that connects to the server we just built.
721 
722First, make sure you have Claude for Desktop installed. [You can install the latest version
723here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
724 
725We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
726 
727For example, if you have [VS Code](https://code.visualstudio.com/) installed:
728 
729```bash macOS/Linux theme={null}
730code ~/Library/Application\ Support/Claude/claude_desktop_config.json
731```
732 
733```powershell Windows theme={null}
734code $env:AppData\Claude\claude_desktop_config.json
735```
736 
737You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
738 
739In this case, we'll add our single weather server like so:
740 
741```json macOS/Linux theme={null}
742{
743 "mcpServers": {
744 "weather": {
745 "command": "node",
746 "args": ["/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js"]
747 }
748 }
749}
750```
751 
752```json Windows theme={null}
753{
754 "mcpServers": {
755 "weather": {
756 "command": "node",
757 "args": ["C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\index.js"]
758 }
759 }
760}
761```
762 
763This tells Claude for Desktop:
764 
7651. There's an MCP server named "weather"
7662. Launch it by running `node /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js`
767 
768Save the file, and restart **Claude for Desktop**.
769 
770**Java**
771 
772> [!NOTE]
773>
774> This is a quickstart demo based on Spring AI MCP auto-configuration and boot starters.
775> To learn how to create sync and async MCP Servers, manually, consult the [Java SDK Server](https://java.sdk.modelcontextprotocol.io/) documentation.
776 
777Let's get started with building our weather server!
778[You can find the complete code for what we'll be building here.](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-stdio-server)
779 
780For more information, see the [MCP Server Boot Starter](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html) reference documentation.
781For manual MCP Server implementation, refer to the [MCP Server Java SDK documentation](https://java.sdk.modelcontextprotocol.io/).
782 
783### Logging in MCP Servers
784 
785When implementing MCP servers, be careful about how you handle logging:
786 
787**For STDIO-based servers:** Never use `System.out.println()` or `System.out.print()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
788 
789**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
790 
791### Best Practices
792 
793* Use a logging library that writes to stderr or files.
794* Ensure any configured logging library will not write to stdout.
795 
796### System requirements
797 
798* Java 17 or higher installed.
799* [Spring Boot 3.3.x](https://docs.spring.io/spring-boot/installing.html) or higher
800 
801### Set up your environment
802 
803Use the [Spring Initializer](https://start.spring.io/) to bootstrap the project.
804 
805You will need to add the following dependencies:
806 
807```xml Maven theme={null}
808<dependencies>
809 <dependency>
810 <groupId>org.springframework.ai</groupId>
811 <artifactId>spring-ai-starter-mcp-server</artifactId>
812 </dependency>
813 
814 <dependency>
815 <groupId>org.springframework</groupId>
816 <artifactId>spring-web</artifactId>
817 </dependency>
818</dependencies>
819```
820 
821```groovy Gradle theme={null}
822dependencies {
823 implementation platform("org.springframework.ai:spring-ai-starter-mcp-server")
824 implementation platform("org.springframework:spring-web")
825}
826```
827 
828Then configure your application by setting the application properties:
829 
830```bash application.properties theme={null}
831spring.main.bannerMode=off
832logging.pattern.console=
833```
834 
835```yaml application.yml theme={null}
836logging:
837 pattern:
838 console:
839spring:
840 main:
841 banner-mode: off
842```
843 
844The [Server Configuration Properties](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html#_configuration_properties) documents all available properties.
845 
846Now let's dive into building your server.
847 
848## Building your server
849 
850### Weather Service
851 
852Let's implement a [WeatherService.java](https://github.com/spring-projects/spring-ai-examples/blob/main/model-context-protocol/weather/starter-stdio-server/src/main/java/org/springframework/ai/mcp/sample/server/WeatherService.java) that uses a REST client to query the data from the National Weather Service API:
853 
854```java theme={null}
855@Service
856public class WeatherService {
857 
858 private final RestClient restClient;
859 
860 public WeatherService() {
861 this.restClient = RestClient.builder()
862 .baseUrl("https://api.weather.gov")
863 .defaultHeader("Accept", "application/geo+json")
864 .defaultHeader("User-Agent", "WeatherApiClient/1.0 ([email protected])")
865 .build();
866 }
867 
868 @Tool(description = "Get weather forecast for a specific latitude/longitude")
869 public String getWeatherForecastByLocation(
870 double latitude, // Latitude coordinate
871 double longitude // Longitude coordinate
872 ) {
873 // Returns detailed forecast including:
874 // - Temperature and unit
875 // - Wind speed and direction
876 // - Detailed forecast description
877 }
878 
879 @Tool(description = "Get weather alerts for a US state")
880 public String getAlerts(
881 @ToolParam(description = "Two-letter US state code (e.g. CA, NY)") String state
882 ) {
883 // Returns active alerts including:
884 // - Event type
885 // - Affected area
886 // - Severity
887 // - Description
888 // - Safety instructions
889 }
890 
891 // ......
892}
893```
894 
895The `@Service` annotation will auto-register the service in your application context.
896The Spring AI `@Tool` annotation makes it easy to create and maintain MCP tools.
897 
898The auto-configuration will automatically register these tools with the MCP server.
899 
900### Create your Boot Application
901 
902```java theme={null}
903@SpringBootApplication
904public class McpServerApplication {
905 
906 public static void main(String[] args) {
907 SpringApplication.run(McpServerApplication.class, args);
908 }
909 
910 @Bean
911 public ToolCallbackProvider weatherTools(WeatherService weatherService) {
912 return MethodToolCallbackProvider.builder().toolObjects(weatherService).build();
913 }
914}
915```
916 
917Uses the `MethodToolCallbackProvider` utils to convert the `@Tools` into actionable callbacks used by the MCP server.
918 
919### Running the server
920 
921Finally, let's build the server:
922 
923```bash theme={null}
924./mvnw clean install
925```
926 
927This will generate an `mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar` file within the `target` folder.
928 
929Let's now test your server from an existing MCP host, Claude for Desktop.
930 
931## Testing your server with Claude for Desktop
932 
933> [!NOTE]
934>
935> Claude for Desktop is not yet available on Linux.
936 
937First, make sure you have Claude for Desktop installed.
938[You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
939 
940We'll need to configure Claude for Desktop for whichever MCP servers you want to use.
941To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor.
942Make sure to create the file if it doesn't exist.
943 
944For example, if you have [VS Code](https://code.visualstudio.com/) installed:
945 
946```bash macOS/Linux theme={null}
947code ~/Library/Application\ Support/Claude/claude_desktop_config.json
948```
949 
950```powershell Windows theme={null}
951code $env:AppData\Claude\claude_desktop_config.json
952```
953 
954You'll then add your servers in the `mcpServers` key.
955The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
956 
957In this case, we'll add our single weather server like so:
958 
959```json macOS/Linux theme={null}
960{
961 "mcpServers": {
962 "spring-ai-mcp-weather": {
963 "command": "java",
964 "args": [
965 "-Dspring.ai.mcp.server.stdio=true",
966 "-jar",
967 "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
968 ]
969 }
970 }
971}
972```
973 
974```json Windows theme={null}
975{
976 "mcpServers": {
977 "spring-ai-mcp-weather": {
978 "command": "java",
979 "args": [
980 "-Dspring.ai.mcp.server.transport=STDIO",
981 "-jar",
982 "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
983 ]
984 }
985 }
986}
987```
988 
989> [!NOTE]
990>
991> Make sure you pass in the absolute path to your server.
992 
993This tells Claude for Desktop:
994 
9951. There's an MCP server named "my-weather-server"
9962. To launch it by running `java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar`
997 
998Save the file, and restart **Claude for Desktop**.
999 
1000## Testing your server with Java client
1001 
1002### Create an MCP Client manually
1003 
1004Use the `McpClient` to connect to the server:
1005 
1006```java theme={null}
1007var stdioParams = ServerParameters.builder("java")
1008 .args("-jar", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar")
1009 .build();
1010 
1011var stdioTransport = new StdioClientTransport(stdioParams);
1012 
1013var mcpClient = McpClient.sync(stdioTransport).build();
1014 
1015mcpClient.initialize();
1016 
1017ListToolsResult toolsList = mcpClient.listTools();
1018 
1019CallToolResult weather = mcpClient.callTool(
1020 new CallToolRequest("getWeatherForecastByLocation",
1021 Map.of("latitude", "47.6062", "longitude", "-122.3321")));
1022 
1023CallToolResult alert = mcpClient.callTool(
1024 new CallToolRequest("getAlerts", Map.of("state", "NY")));
1025 
1026mcpClient.closeGracefully();
1027```
1028 
1029### Use MCP Client Boot Starter
1030 
1031Create a new boot starter application using the `spring-ai-starter-mcp-client` dependency:
1032 
1033```xml theme={null}
1034<dependency>
1035 <groupId>org.springframework.ai</groupId>
1036 <artifactId>spring-ai-starter-mcp-client</artifactId>
1037</dependency>
1038```
1039 
1040and set the `spring.ai.mcp.client.stdio.servers-configuration` property to point to your `claude_desktop_config.json`.
1041You can reuse the existing Anthropic Desktop configuration:
1042 
1043```properties theme={null}
1044spring.ai.mcp.client.stdio.servers-configuration=file:PATH/TO/claude_desktop_config.json
1045```
1046 
1047When you start your client application, the auto-configuration will automatically create MCP clients from the claude\_desktop\_config.json.
1048 
1049For more information, see the [MCP Client Boot Starters](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-client-boot-starter-docs.html) reference documentation.
1050 
1051## More Java MCP Server examples
1052 
1053The [starter-webflux-server](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-webflux-server) demonstrates how to create an MCP server using SSE transport.
1054It showcases how to define and register MCP Tools, Resources, and Prompts, using the Spring Boot's auto-configuration capabilities.
1055 
1056**Kotlin**
1057 
1058Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/weather-stdio-server)
1059 
1060### Prerequisite knowledge
1061 
1062This quickstart assumes you have familiarity with:
1063 
1064* Kotlin
1065* LLMs like Claude
1066 
1067### Logging in MCP Servers
1068 
1069When implementing MCP servers, be careful about how you handle logging:
1070 
1071**For STDIO-based servers:** Never use `println()`, as it writes to standard output (stdout) by default. Writing to stdout will corrupt the JSON-RPC messages and break your server.
1072 
1073**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
1074 
1075### Best Practices
1076 
1077* Use a logging library that writes to stderr or files.
1078 
1079### System requirements
1080 
1081* JDK 11 or higher installed.
1082 
1083### Set up your environment
1084 
1085First, let's install `java` and `gradle` if you haven't already.
1086You can download `java` from [official Oracle JDK website](https://www.oracle.com/java/technologies/downloads/).
1087Verify your `java` installation:
1088 
1089```bash theme={null}
1090java --version
1091```
1092 
1093Now, let's create and set up your project:
1094 
1095```bash macOS/Linux theme={null}
1096# Create a new directory for our project
1097mkdir weather
1098cd weather
1099 
1100# Initialize a new kotlin project
1101gradle init
1102```
1103 
1104```powershell Windows theme={null}
1105# Create a new directory for our project
1106md weather
1107cd weather
1108 
1109# Initialize a new kotlin project
1110gradle init
1111```
1112 
1113After running `gradle init`, select **Application** as the project type, **Kotlin** as the programming language.
1114 
1115Alternatively, you can create a Kotlin application using the [IntelliJ IDEA project wizard](https://kotlinlang.org/docs/jvm-get-started.html).
1116 
1117After creating the project, replace the contents of your `build.gradle.kts` with:
1118 
1119```kotlin build.gradle.kts theme={null}
1120// Check latest versions at https://github.com/modelcontextprotocol/kotlin-sdk/releases
1121val mcpVersion = "0.9.0"
1122val ktorVersion = "3.2.3"
1123val slf4jVersion = "2.0.17"
1124 
1125plugins {
1126 kotlin("jvm") version "2.3.20"
1127 kotlin("plugin.serialization") version "2.3.20"
1128 id("com.gradleup.shadow") version "8.3.9"
1129 application
1130}
1131 
1132application {
1133 mainClass.set("MainKt")
1134}
1135 
1136dependencies {
1137 implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion")
1138 implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion")
1139 implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")
1140 implementation("io.ktor:ktor-client-cio:$ktorVersion")
1141 implementation("org.slf4j:slf4j-simple:$slf4jVersion")
1142}
1143```
1144 
1145Verify that everything is set up correctly:
1146 
1147```bash theme={null}
1148./gradlew build
1149```
1150 
1151Now let's dive into building your server.
1152 
1153## Building your server
1154 
1155### Setting up the instance
1156 
1157Add a server initialization function:
1158 
1159```kotlin theme={null}
1160fun runMcpServer() {
1161 val server = Server(
1162 Implementation(
1163 name = "weather",
1164 version = "1.0.0",
1165 ),
1166 ServerOptions(
1167 capabilities = ServerCapabilities(tools = ServerCapabilities.Tools(listChanged = true)),
1168 ),
1169 )
1170 
1171 // register tools on server here
1172 
1173 val transport = StdioServerTransport(
1174 System.`in`.asInput(),
1175 System.out.asSink().buffered(),
1176 )
1177 
1178 runBlocking {
1179 val session = server.createSession(transport)
1180 val done = Job()
1181 session.onClose {
1182 done.complete()
1183 }
1184 done.join()
1185 }
1186}
1187```
1188 
1189### Weather API helper functions
1190 
1191Next, let's add functions and data classes for querying and converting responses from the National Weather Service API:
1192 
1193```kotlin theme={null}
1194val httpClient = HttpClient(CIO) {
1195 defaultRequest {
1196 url("https://api.weather.gov")
1197 headers {
1198 append("Accept", "application/geo+json")
1199 append("User-Agent", "WeatherApiClient/1.0")
1200 }
1201 contentType(ContentType.Application.Json)
1202 }
1203 install(ContentNegotiation) {
1204 json(Json { ignoreUnknownKeys = true })
1205 }
1206}
1207 
1208// Extension function to fetch weather alerts for a given state
1209suspend fun HttpClient.getAlerts(state: String): List<String> {
1210 val alerts = this.get("/alerts/active/area/$state").body<AlertsResponse>()
1211 return alerts.features.map { feature ->
1891212 """
190 url = f"{NWS_API_BASE}/alerts/active/area/{state}"
191 data = await make_nws_request(url)
192 
193 if not data or "features" not in data:
194 return "Unable to fetch alerts or no alerts found."
195 
196 if not data["features"]:
197 return "No active alerts for this state."
198 
199 alerts = [format_alert(feature) for feature in data["features"]]
200 return "\n---\n".join(alerts)
201 
202 
203 @mcp.tool()
204 async def get_forecast(latitude: float, longitude: float) -> str:
205 """Get weather forecast for a location.
206 
207 Args:
208 latitude: Latitude of the location
209 longitude: Longitude of the location
1213 Event: ${feature.properties.event}
1214 Area: ${feature.properties.areaDesc}
1215 Severity: ${feature.properties.severity}
1216 Status: ${feature.properties.status}
1217 Headline: ${feature.properties.headline}
1218 """.trimIndent()
1219 }
1220}
1221 
1222// Extension function to fetch forecast information for given latitude and longitude
1223suspend fun HttpClient.getForecast(latitude: Double, longitude: Double): List<String> {
1224 val points = this.get("/points/$latitude,$longitude").body<PointsResponse>()
1225 val forecastUrl = points.properties.forecast ?: error("No forecast URL available")
1226 val forecast = this.get(forecastUrl).body<ForecastResponse>()
1227 return forecast.properties.periods.map { period ->
2101228 """
211 # First get the forecast grid endpoint
212 points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
213 points_data = await make_nws_request(points_url)
214 
215 if not points_data:
216 return "Unable to fetch forecast data for this location."
217 
218 # Get the forecast URL from the points response
219 forecast_url = points_data["properties"]["forecast"]
220 forecast_data = await make_nws_request(forecast_url)
221 
222 if not forecast_data:
223 return "Unable to fetch detailed forecast."
224 
225 # Format the periods into a readable forecast
226 periods = forecast_data["properties"]["periods"]
227 forecasts = []
228 for period in periods[:5]: # Only show next 5 periods
229 forecast = f"""
230 {period["name"]}:
231 Temperature: {period["temperature"]}°{period["temperatureUnit"]}
232 Wind: {period["windSpeed"]} {period["windDirection"]}
233 Forecast: {period["detailedForecast"]}
234 """
235 forecasts.append(forecast)
236 
237 return "\n---\n".join(forecasts)
238 ```
239 
240 ### Running the server
241 
242 Finally, let's initialize and run the server:
243 
244 ```python theme={null}
245 def main():
246 # Initialize and run the server
247 mcp.run(transport="stdio")
248 
249 
250 if __name__ == "__main__":
251 main()
252 ```
253 
254 Your server is complete! Run `uv run weather.py` to start the MCP server, which will listen for messages from MCP hosts.
255 
256 Let's now test your server from an existing MCP host, Claude for Desktop.
257 
258 ## Testing your server with Claude for Desktop
259 
260 <Note>
261 Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/docs/2025-11-25/develop/build-client) tutorial to build an MCP client that connects to the server we just built.
262 </Note>
263 
264 First, make sure you have Claude for Desktop installed. [You can install the latest version
265 here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
266 
267 We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
268 
269 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
270 
271 <CodeGroup>
272 ```bash macOS/Linux theme={null}
273 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
274 ```
275 
276 ```powershell Windows theme={null}
277 code $env:AppData\Claude\claude_desktop_config.json
278 ```
279 </CodeGroup>
280 
281 You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
282 
283 In this case, we'll add our single weather server like so:
284 
285 <CodeGroup>
286 ```json macOS/Linux theme={null}
287 {
288 "mcpServers": {
289 "weather": {
290 "command": "uv",
291 "args": [
292 "--directory",
293 "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
294 "run",
295 "weather.py"
296 ]
297 }
1229 ${period.name}:
1230 Temperature: ${period.temperature}°${period.temperatureUnit}
1231 Wind: ${period.windSpeed} ${period.windDirection}
1232 ${period.shortForecast}
1233 """.trimIndent()
1234 }
1235}
1236 
1237@Serializable
1238data class PointsResponse(val properties: PointsProperties)
1239 
1240@Serializable
1241data class PointsProperties(val forecast: String? = null)
1242 
1243@Serializable
1244data class ForecastResponse(val properties: ForecastProperties)
1245 
1246@Serializable
1247data class ForecastProperties(val periods: List<ForecastPeriod> = emptyList())
1248 
1249@Serializable
1250data class ForecastPeriod(
1251 val name: String? = null,
1252 val temperature: Int? = null,
1253 val temperatureUnit: String? = null,
1254 val windSpeed: String? = null,
1255 val windDirection: String? = null,
1256 val shortForecast: String? = null,
1257)
1258 
1259@Serializable
1260data class AlertsResponse(val features: List<AlertFeature> = emptyList())
1261 
1262@Serializable
1263data class AlertFeature(val properties: AlertProperties)
1264 
1265@Serializable
1266data class AlertProperties(
1267 val event: String? = null,
1268 val areaDesc: String? = null,
1269 val severity: String? = null,
1270 val status: String? = null,
1271 val headline: String? = null,
1272)
1273```
1274 
1275### Implementing tool execution
1276 
1277The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
1278 
1279```kotlin theme={null}
1280// Register weather tools
1281 
1282server.addTool(
1283 name = "get_alerts",
1284 description = "Get weather alerts for a US state. Input is a two-letter US state code (e.g. CA, NY)",
1285 inputSchema = ToolSchema(
1286 properties = buildJsonObject {
1287 putJsonObject("state") {
1288 put("type", "string")
1289 put("description", "Two-letter US state code (e.g. CA, NY)")
1290 }
1291 },
1292 required = listOf("state"),
1293 ),
1294) { request ->
1295 val state = request.arguments?.get("state")?.jsonPrimitive?.content
1296 ?: return@addTool CallToolResult(
1297 content = listOf(TextContent("The 'state' parameter is required.")),
1298 )
1299 
1300 val alerts = httpClient.getAlerts(state)
1301 CallToolResult(content = alerts.map { TextContent(it) })
1302}
1303 
1304server.addTool(
1305 name = "get_forecast",
1306 description = "Get weather forecast for a location. Note: only US locations are supported by the NWS API.",
1307 inputSchema = ToolSchema(
1308 properties = buildJsonObject {
1309 putJsonObject("latitude") {
1310 put("type", "number")
1311 put("description", "Latitude of the location")
1312 }
1313 putJsonObject("longitude") {
1314 put("type", "number")
1315 put("description", "Longitude of the location")
1316 }
1317 },
1318 required = listOf("latitude", "longitude"),
1319 ),
1320) { request ->
1321 val latitude = request.arguments?.get("latitude")?.jsonPrimitive?.doubleOrNull
1322 val longitude = request.arguments?.get("longitude")?.jsonPrimitive?.doubleOrNull
1323 if (latitude == null || longitude == null) {
1324 return@addTool CallToolResult(
1325 content = listOf(TextContent("The 'latitude' and 'longitude' parameters are required.")),
1326 )
1327 }
1328 
1329 val forecast = httpClient.getForecast(latitude, longitude)
1330 CallToolResult(content = forecast.map { TextContent(it) })
1331}
1332```
1333 
1334### Running the server
1335 
1336Finally, implement the main function to run the server:
1337 
1338```kotlin theme={null}
1339fun main() = runMcpServer()
1340```
1341 
1342You can run the server directly during development:
1343 
1344```bash theme={null}
1345./gradlew run
1346```
1347 
1348For production use, build the shadow JAR:
1349 
1350```bash theme={null}
1351./gradlew build
1352java -jar build/libs/weather-0.1.0-all.jar
1353```
1354 
1355Let's now test your server from an existing MCP host, Claude for Desktop.
1356 
1357## Testing your server with Claude for Desktop
1358 
1359> [!NOTE]
1360>
1361> Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/docs/2025-11-25/develop/build-client) tutorial to build an MCP client that connects to the server we just built.
1362 
1363First, make sure you have Claude for Desktop installed. [You can install the latest version
1364here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
1365 
1366We'll need to configure Claude for Desktop for whichever MCP servers you want to use.
1367To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor.
1368Make sure to create the file if it doesn't exist.
1369 
1370For example, if you have [VS Code](https://code.visualstudio.com/) installed:
1371 
1372```bash macOS/Linux theme={null}
1373code ~/Library/Application\ Support/Claude/claude_desktop_config.json
1374```
1375 
1376```powershell Windows theme={null}
1377code $env:AppData\Claude\claude_desktop_config.json
1378```
1379 
1380You'll then add your servers in the `mcpServers` key.
1381The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
1382 
1383In this case, we'll add our single weather server like so:
1384 
1385```json macOS/Linux theme={null}
1386{
1387 "mcpServers": {
1388 "weather": {
1389 "command": "java",
1390 "args": [
1391 "-jar",
1392 "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/libs/weather-0.1.0-all.jar"
1393 ]
1394 }
1395 }
1396}
1397```
1398 
1399```json Windows theme={null}
1400{
1401 "mcpServers": {
1402 "weather": {
1403 "command": "java",
1404 "args": [
1405 "-jar",
1406 "C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\libs\\weather-0.1.0-all.jar"
1407 ]
1408 }
1409 }
1410}
1411```
1412 
1413This tells Claude for Desktop:
1414 
14151. There's an MCP server named "weather"
14162. Launch it by running `java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/libs/weather-0.1.0-all.jar`
1417 
1418Save the file, and restart **Claude for Desktop**.
1419 
1420**C#**
1421 
1422Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/csharp-sdk/tree/main/samples/QuickstartWeatherServer)
1423 
1424### Prerequisite knowledge
1425 
1426This quickstart assumes you have familiarity with:
1427 
1428* C#
1429* LLMs like Claude
1430* .NET 8 or higher
1431 
1432### Logging in MCP Servers
1433 
1434When implementing MCP servers, be careful about how you handle logging:
1435 
1436**For STDIO-based servers:** Never use `Console.WriteLine()` or `Console.Write()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
1437 
1438**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
1439 
1440### Best Practices
1441 
1442* Use a logging library that writes to stderr or files.
1443 
1444### System requirements
1445 
1446* [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) or higher installed.
1447 
1448### Set up your environment
1449 
1450First, let's install `dotnet` if you haven't already. You can download `dotnet` from [official Microsoft .NET website](https://dotnet.microsoft.com/download/). Verify your `dotnet` installation:
1451 
1452```bash theme={null}
1453dotnet --version
1454```
1455 
1456Now, let's create and set up your project:
1457 
1458```bash macOS/Linux theme={null}
1459# Create a new directory for our project
1460mkdir weather
1461cd weather
1462# Initialize a new C# project
1463dotnet new console
1464```
1465 
1466```powershell Windows theme={null}
1467# Create a new directory for our project
1468mkdir weather
1469cd weather
1470# Initialize a new C# project
1471dotnet new console
1472```
1473 
1474After running `dotnet new console`, you will be presented with a new C# project.
1475You can open the project in your favorite IDE, such as [Visual Studio](https://visualstudio.microsoft.com/) or [Rider](https://www.jetbrains.com/rider/).
1476Alternatively, you can create a C# application using the [Visual Studio project wizard](https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-console?view=vs-2022).
1477After creating the project, add NuGet package for the Model Context Protocol SDK and hosting:
1478 
1479```bash theme={null}
1480# Add the Model Context Protocol SDK NuGet package
1481dotnet add package ModelContextProtocol --prerelease
1482# Add the .NET Hosting NuGet package
1483dotnet add package Microsoft.Extensions.Hosting
1484```
1485 
1486Now let’s dive into building your server.
1487 
1488## Building your server
1489 
1490Open the `Program.cs` file in your project and replace its contents with the following code:
1491 
1492```csharp theme={null}
1493using Microsoft.Extensions.DependencyInjection;
1494using Microsoft.Extensions.Hosting;
1495using ModelContextProtocol;
1496using System.Net.Http.Headers;
1497 
1498var builder = Host.CreateEmptyApplicationBuilder(settings: null);
1499 
1500builder.Services.AddMcpServer()
1501 .WithStdioServerTransport()
1502 .WithToolsFromAssembly();
1503 
1504builder.Services.AddSingleton(_ =>
1505{
1506 var client = new HttpClient() { BaseAddress = new Uri("https://api.weather.gov") };
1507 client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("weather-tool", "1.0"));
1508 return client;
1509});
1510 
1511var app = builder.Build();
1512 
1513await app.RunAsync();
1514```
1515 
1516> [!NOTE]
1517>
1518> When creating the `ApplicationHostBuilder`, ensure you use `CreateEmptyApplicationBuilder` instead of `CreateDefaultBuilder`. This ensures that the server does not write any additional messages to the console. This is only necessary for servers using STDIO transport.
1519 
1520This code sets up a basic console application that uses the Model Context Protocol SDK to create an MCP server with standard I/O transport.
1521 
1522### Weather API helper functions
1523 
1524Create an extension class for `HttpClient` which helps simplify JSON request handling:
1525 
1526```csharp theme={null}
1527using System.Text.Json;
1528 
1529internal static class HttpClientExt
1530{
1531 public static async Task<JsonDocument> ReadJsonDocumentAsync(this HttpClient client, string requestUri)
1532 {
1533 using var response = await client.GetAsync(requestUri);
1534 response.EnsureSuccessStatusCode();
1535 return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
1536 }
1537}
1538```
1539 
1540Next, define a class with the tool execution handlers for querying and converting responses from the National Weather Service API:
1541 
1542```csharp theme={null}
1543using ModelContextProtocol.Server;
1544using System.ComponentModel;
1545using System.Globalization;
1546using System.Text.Json;
1547 
1548namespace QuickstartWeatherServer.Tools;
1549 
1550[McpServerToolType]
1551public static class WeatherTools
1552{
1553 [McpServerTool, Description("Get weather alerts for a US state code.")]
1554 public static async Task<string> GetAlerts(
1555 HttpClient client,
1556 [Description("The US state code to get alerts for.")] string state)
1557 {
1558 using var jsonDocument = await client.ReadJsonDocumentAsync($"/alerts/active/area/{state}");
1559 var jsonElement = jsonDocument.RootElement;
1560 var alerts = jsonElement.GetProperty("features").EnumerateArray();
1561 
1562 if (!alerts.Any())
1563 {
1564 return "No active alerts for this state.";
2981565 }
1566 
1567 return string.Join("\n--\n", alerts.Select(alert =>
1568 {
1569 JsonElement properties = alert.GetProperty("properties");
1570 return $"""
1571 Event: {properties.GetProperty("event").GetString()}
1572 Area: {properties.GetProperty("areaDesc").GetString()}
1573 Severity: {properties.GetProperty("severity").GetString()}
1574 Description: {properties.GetProperty("description").GetString()}
1575 Instruction: {properties.GetProperty("instruction").GetString()}
1576 """;
1577 }));
1578 }
1579 
1580 [McpServerTool, Description("Get weather forecast for a location.")]
1581 public static async Task<string> GetForecast(
1582 HttpClient client,
1583 [Description("Latitude of the location.")] double latitude,
1584 [Description("Longitude of the location.")] double longitude)
1585 {
1586 var pointUrl = string.Create(CultureInfo.InvariantCulture, $"/points/{latitude},{longitude}");
1587 using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);
1588 var forecastUrl = jsonDocument.RootElement.GetProperty("properties").GetProperty("forecast").GetString()
1589 ?? throw new Exception($"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}");
1590 
1591 using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl);
1592 var periods = forecastDocument.RootElement.GetProperty("properties").GetProperty("periods").EnumerateArray();
1593 
1594 return string.Join("\n---\n", periods.Select(period => $"""
1595 {period.GetProperty("name").GetString()}
1596 Temperature: {period.GetProperty("temperature").GetInt32()}°F
1597 Wind: {period.GetProperty("windSpeed").GetString()} {period.GetProperty("windDirection").GetString()}
1598 Forecast: {period.GetProperty("detailedForecast").GetString()}
1599 """));
1600 }
1601}
1602```
1603 
1604### Running the server
1605 
1606Finally, run the server using the following command:
1607 
1608```bash theme={null}
1609dotnet run
1610```
1611 
1612This will start the server and listen for incoming requests on standard input/output.
1613 
1614## Testing your server with Claude for Desktop
1615 
1616> [!NOTE]
1617>
1618> Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/docs/2025-11-25/develop/build-client) tutorial to build an MCP client that connects to the server we just built.
1619 
1620First, make sure you have Claude for Desktop installed. [You can install the latest version
1621here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
1622We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
1623For example, if you have [VS Code](https://code.visualstudio.com/) installed:
1624 
1625```bash macOS/Linux theme={null}
1626code ~/Library/Application\ Support/Claude/claude_desktop_config.json
1627```
1628 
1629```powershell Windows theme={null}
1630code $env:AppData\Claude\claude_desktop_config.json
1631```
1632 
1633You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
1634In this case, we'll add our single weather server like so:
1635 
1636```json macOS/Linux theme={null}
1637{
1638 "mcpServers": {
1639 "weather": {
1640 "command": "dotnet",
1641 "args": ["run", "--project", "/ABSOLUTE/PATH/TO/PROJECT", "--no-build"]
1642 }
1643 }
1644}
1645```
1646 
1647```json Windows theme={null}
1648{
1649 "mcpServers": {
1650 "weather": {
1651 "command": "dotnet",
1652 "args": [
1653 "run",
1654 "--project",
1655 "C:\\ABSOLUTE\\PATH\\TO\\PROJECT",
1656 "--no-build"
1657 ]
1658 }
1659 }
1660}
1661```
1662 
1663This tells Claude for Desktop:
1664 
16651. There's an MCP server named "weather"
16662. Launch it by running `dotnet run /ABSOLUTE/PATH/TO/PROJECT`
1667 Save the file, and restart **Claude for Desktop**.
1668 
1669**Ruby**
1670 
1671Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-ruby)
1672 
1673### Prerequisite knowledge
1674 
1675This quickstart assumes you have familiarity with:
1676 
1677* Ruby
1678* LLMs like Claude
1679 
1680### Logging in MCP Servers
1681 
1682When implementing MCP servers, be careful about how you handle logging:
1683 
1684**For STDIO-based servers:** Never use `puts` or `print`, as they write to standard output (stdout) by default. Writing to stdout will corrupt the JSON-RPC messages and break your server.
1685 
1686**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
1687 
1688### Best Practices
1689 
1690* Use a logging library that writes to stderr or files.
1691 
1692### Quick Examples
1693 
1694```ruby theme={null}
1695# ❌ Bad (STDIO)
1696puts "Processing request"
1697 
1698# ✅ Good (STDIO)
1699require "logger"
1700logger = Logger.new($stderr)
1701logger.info("Processing request")
1702```
1703 
1704### System requirements
1705 
1706* Ruby 2.7 or higher installed.
1707 
1708### Set up your environment
1709 
1710First, let's make sure you have Ruby installed. You can check by running:
1711 
1712```bash theme={null}
1713ruby --version
1714```
1715 
1716Now, let's create and set up our project:
1717 
1718```bash macOS/Linux theme={null}
1719# Create a new directory for our project
1720mkdir weather
1721cd weather
1722 
1723# Create a Gemfile
1724bundle init
1725 
1726# Add the MCP SDK dependency
1727bundle add mcp
1728 
1729# Create our server file
1730touch weather.rb
1731```
1732 
1733```powershell Windows theme={null}
1734# Create a new directory for our project
1735mkdir weather
1736cd weather
1737 
1738# Create a Gemfile
1739bundle init
1740 
1741# Add the MCP SDK dependency
1742bundle add mcp
1743 
1744# Create our server file
1745new-item weather.rb
1746```
1747 
1748Now let's dive into building your server.
1749 
1750## Building your server
1751 
1752### Importing packages and setting up constants
1753 
1754Open `weather.rb` and add these requires and constants at the top:
1755 
1756```ruby theme={null}
1757require "json"
1758require "mcp"
1759require "net/http"
1760require "uri"
1761 
1762NWS_API_BASE = "https://api.weather.gov"
1763USER_AGENT = "weather-app/1.0"
1764```
1765 
1766The `mcp` gem provides the Model Context Protocol SDK for Ruby, with classes for server implementation and stdio transport.
1767 
1768### Helper methods
1769 
1770Next, let's add helper methods for querying and formatting data from the National Weather Service API:
1771 
1772```ruby theme={null}
1773module HelperMethods
1774 def make_nws_request(url)
1775 uri = URI(url)
1776 request = Net::HTTP::Get.new(uri)
1777 request["User-Agent"] = USER_AGENT
1778 request["Accept"] = "application/geo+json"
1779 
1780 response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
1781 http.request(request)
1782 end
1783 
1784 raise "HTTP #{response.code}: #{response.message}" unless response.is_a?(Net::HTTPSuccess)
1785 
1786 JSON.parse(response.body)
1787 end
1788 
1789 def format_alert(feature)
1790 properties = feature["properties"]
1791 
1792 <<~ALERT
1793 Event: #{properties["event"] || "Unknown"}
1794 Area: #{properties["areaDesc"] || "Unknown"}
1795 Severity: #{properties["severity"] || "Unknown"}
1796 Description: #{properties["description"] || "No description available"}
1797 Instructions: #{properties["instruction"] || "No specific instructions provided"}
1798 ALERT
1799 end
1800end
1801```
1802 
1803### Implementing tool execution
1804 
1805Now let's define our tool classes. Each tool subclasses `MCP::Tool` and implements the tool logic:
1806 
1807```ruby theme={null}
1808class GetAlerts < MCP::Tool
1809 extend HelperMethods
1810 
1811 tool_name "get_alerts"
1812 description "Get weather alerts for a US state"
1813 input_schema(
1814 properties: {
1815 state: {
1816 type: "string",
1817 description: "Two-letter US state code (e.g. CA, NY)"
2991818 }
300 ```
301 
302 ```json Windows theme={null}
303 {
304 "mcpServers": {
305 "weather": {
306 "command": "uv",
307 "args": [
308 "--directory",
309 "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather",
310 "run",
311 "weather.py"
312 ]
313 }
1819 },
1820 required: ["state"]
1821 )
1822 
1823 def self.call(state:)
1824 url = "#{NWS_API_BASE}/alerts/active/area/#{state.upcase}"
1825 data = make_nws_request(url)
1826 
1827 if data["features"].empty?
1828 return MCP::Tool::Response.new([{
1829 type: "text",
1830 text: "No active alerts for this state."
1831 }])
1832 end
1833 
1834 alerts = data["features"].map { |feature| format_alert(feature) }
1835 MCP::Tool::Response.new([{
1836 type: "text",
1837 text: alerts.join("\n---\n")
1838 }])
1839 end
1840end
1841 
1842class GetForecast < MCP::Tool
1843 extend HelperMethods
1844 
1845 tool_name "get_forecast"
1846 description "Get weather forecast for a location"
1847 input_schema(
1848 properties: {
1849 latitude: {
1850 type: "number",
1851 description: "Latitude of the location"
1852 },
1853 longitude: {
1854 type: "number",
1855 description: "Longitude of the location"
1856 }
1857 },
1858 required: ["latitude", "longitude"]
1859 )
1860 
1861 def self.call(latitude:, longitude:)
1862 # First get the forecast grid endpoint.
1863 points_url = "#{NWS_API_BASE}/points/#{latitude},#{longitude}"
1864 points_data = make_nws_request(points_url)
1865 
1866 # Get the forecast URL from the points response.
1867 forecast_url = points_data["properties"]["forecast"]
1868 forecast_data = make_nws_request(forecast_url)
1869 
1870 # Format the periods into a readable forecast.
1871 periods = forecast_data["properties"]["periods"]
1872 forecasts = periods.first(5).map do |period|
1873 <<~FORECAST
1874 #{period["name"]}:
1875 Temperature: #{period["temperature"]}°#{period["temperatureUnit"]}
1876 Wind: #{period["windSpeed"]} #{period["windDirection"]}
1877 Forecast: #{period["detailedForecast"]}
1878 FORECAST
1879 end
1880 
1881 MCP::Tool::Response.new([{
1882 type: "text",
1883 text: forecasts.join("\n---\n")
1884 }])
1885 end
1886end
1887```
1888 
1889### Running the server
1890 
1891Finally, initialize and run the server:
1892 
1893```ruby theme={null}
1894server = MCP::Server.new(
1895 name: "weather",
1896 version: "1.0.0",
1897 tools: [GetAlerts, GetForecast]
1898)
1899 
1900transport = MCP::Server::Transports::StdioTransport.new(server)
1901transport.open
1902```
1903 
1904Your server is complete! Run `bundle exec ruby weather.rb` to start the MCP server, which will listen for messages from MCP hosts.
1905 
1906Let's now test your server from an existing MCP host, Claude for Desktop.
1907 
1908## Testing your server with Claude for Desktop
1909 
1910> [!NOTE]
1911>
1912> Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/docs/2025-11-25/develop/build-client) tutorial to build an MCP client that connects to the server we just built.
1913 
1914First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
1915 
1916We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
1917 
1918For example, if you have [VS Code](https://code.visualstudio.com/) installed:
1919 
1920```bash macOS/Linux theme={null}
1921code ~/Library/Application\ Support/Claude/claude_desktop_config.json
1922```
1923 
1924```powershell Windows theme={null}
1925code $env:AppData\Claude\claude_desktop_config.json
1926```
1927 
1928You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
1929 
1930In this case, we'll add our single weather server like so:
1931 
1932```json macOS/Linux theme={null}
1933{
1934 "mcpServers": {
1935 "weather": {
1936 "command": "bundle",
1937 "args": ["exec", "ruby", "weather.rb"],
1938 "cwd": "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather"
1939 }
1940 }
1941}
1942```
1943 
1944```json Windows theme={null}
1945{
1946 "mcpServers": {
1947 "weather": {
1948 "command": "bundle",
1949 "args": ["exec", "ruby", "weather.rb"],
1950 "cwd": "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather"
1951 }
1952 }
1953}
1954```
1955 
1956> [!NOTE]
1957>
1958> Make sure you pass in the absolute path to your project directory in the `cwd` field. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt from your project directory. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path.
1959 
1960This tells Claude for Desktop:
1961 
19621. There's an MCP server named "weather"
19632. Launch it by running `bundle exec ruby weather.rb` in the specified directory
1964 
1965Save the file, and restart **Claude for Desktop**.
1966 
1967**Rust**
1968 
1969Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-rust)
1970 
1971### Prerequisite knowledge
1972 
1973This quickstart assumes you have familiarity with:
1974 
1975* Rust programming language
1976* Async/await in Rust
1977* LLMs like Claude
1978 
1979### Logging in MCP Servers
1980 
1981When implementing MCP servers, be careful about how you handle logging:
1982 
1983**For STDIO-based servers:** Never use `println!()` or `print!()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
1984 
1985**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
1986 
1987### Best Practices
1988 
1989* Use a logging library that writes to stderr or files, such as `tracing` or `log` in Rust.
1990* Configure your logging framework to avoid stdout output.
1991 
1992### Quick Examples
1993 
1994```rust theme={null}
1995// ❌ Bad (STDIO)
1996println!("Processing request");
1997 
1998// ✅ Good (STDIO)
1999eprintln!("Processing request"); // writes to stderr
2000```
2001 
2002### System requirements
2003 
2004* Rust 1.70 or higher installed.
2005* Cargo (comes with Rust installation).
2006 
2007### Set up your environment
2008 
2009First, let's install Rust if you haven't already. You can install Rust from [rust-lang.org](https://www.rust-lang.org/tools/install):
2010 
2011```bash macOS/Linux theme={null}
2012curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
2013```
2014 
2015```powershell Windows theme={null}
2016# Download and run rustup-init.exe from https://rustup.rs/
2017```
2018 
2019Verify your Rust installation:
2020 
2021```bash theme={null}
2022rustc --version
2023cargo --version
2024```
2025 
2026Now, let's create and set up our project:
2027 
2028```bash macOS/Linux theme={null}
2029# Create a new Rust project
2030cargo new weather
2031cd weather
2032```
2033 
2034```powershell Windows theme={null}
2035# Create a new Rust project
2036cargo new weather
2037cd weather
2038```
2039 
2040Update your `Cargo.toml` to add the required dependencies:
2041 
2042```toml Cargo.toml theme={null}
2043[package]
2044name = "weather"
2045version = "0.1.0"
2046edition = "2024"
2047 
2048[dependencies]
2049rmcp = { version = "0.3", features = ["server", "macros", "transport-io"] }
2050tokio = { version = "1.46", features = ["full"] }
2051reqwest = { version = "0.12", features = ["json"] }
2052serde = { version = "1.0", features = ["derive"] }
2053serde_json = "1.0"
2054anyhow = "1.0"
2055tracing = "0.1"
2056tracing-subscriber = { version = "0.3", features = ["env-filter", "std", "fmt"] }
2057```
2058 
2059Now let's dive into building your server.
2060 
2061## Building your server
2062 
2063### Importing packages and constants
2064 
2065Open `src/main.rs` and add these imports and constants at the top:
2066 
2067```rust theme={null}
2068use anyhow::Result;
2069use rmcp::{
2070 ServerHandler, ServiceExt,
2071 handler::server::{router::tool::ToolRouter, tool::Parameters},
2072 model::*,
2073 schemars, tool, tool_handler, tool_router,
2074};
2075use serde::Deserialize;
2076use serde::de::DeserializeOwned;
2077 
2078const NWS_API_BASE: &str = "https://api.weather.gov";
2079const USER_AGENT: &str = "weather-app/1.0";
2080```
2081 
2082The `rmcp` crate provides the Model Context Protocol SDK for Rust, with features for server implementation, procedural macros, and stdio transport.
2083 
2084### Data structures
2085 
2086Next, let's define the data structures for deserializing responses from the National Weather Service API:
2087 
2088```rust theme={null}
2089#[derive(Debug, Deserialize)]
2090struct AlertsResponse {
2091 features: Vec<AlertFeature>,
2092}
2093 
2094#[derive(Debug, Deserialize)]
2095struct AlertFeature {
2096 properties: AlertProperties,
2097}
2098 
2099#[derive(Debug, Deserialize)]
2100struct AlertProperties {
2101 event: Option<String>,
2102 #[serde(rename = "areaDesc")]
2103 area_desc: Option<String>,
2104 severity: Option<String>,
2105 description: Option<String>,
2106 instruction: Option<String>,
2107}
2108 
2109#[derive(Debug, Deserialize)]
2110struct PointsResponse {
2111 properties: PointsProperties,
2112}
2113 
2114#[derive(Debug, Deserialize)]
2115struct PointsProperties {
2116 forecast: String,
2117}
2118 
2119#[derive(Debug, Deserialize)]
2120struct ForecastResponse {
2121 properties: ForecastProperties,
2122}
2123 
2124#[derive(Debug, Deserialize)]
2125struct ForecastProperties {
2126 periods: Vec<ForecastPeriod>,
2127}
2128 
2129#[derive(Debug, Deserialize)]
2130struct ForecastPeriod {
2131 name: String,
2132 temperature: i32,
2133 #[serde(rename = "temperatureUnit")]
2134 temperature_unit: String,
2135 #[serde(rename = "windSpeed")]
2136 wind_speed: String,
2137 #[serde(rename = "windDirection")]
2138 wind_direction: String,
2139 #[serde(rename = "detailedForecast")]
2140 detailed_forecast: String,
2141}
2142```
2143 
2144Now define the request types that MCP clients will send:
2145 
2146```rust theme={null}
2147#[derive(serde::Deserialize, schemars::JsonSchema)]
2148pub struct MCPForecastRequest {
2149 latitude: f32,
2150 longitude: f32,
2151}
2152 
2153#[derive(serde::Deserialize, schemars::JsonSchema)]
2154pub struct MCPAlertRequest {
2155 state: String,
2156}
2157```
2158 
2159### Helper functions
2160 
2161Add helper functions for making API requests and formatting responses:
2162 
2163```rust theme={null}
2164async fn make_nws_request<T: DeserializeOwned>(url: &str) -> Result<T> {
2165 let client = reqwest::Client::new();
2166 let rsp = client
2167 .get(url)
2168 .header(reqwest::header::USER_AGENT, USER_AGENT)
2169 .header(reqwest::header::ACCEPT, "application/geo+json")
2170 .send()
2171 .await?
2172 .error_for_status()?;
2173 Ok(rsp.json::<T>().await?)
2174}
2175 
2176fn format_alert(feature: &AlertFeature) -> String {
2177 let props = &feature.properties;
2178 format!(
2179 "Event: {}\nArea: {}\nSeverity: {}\nDescription: {}\nInstructions: {}",
2180 props.event.as_deref().unwrap_or("Unknown"),
2181 props.area_desc.as_deref().unwrap_or("Unknown"),
2182 props.severity.as_deref().unwrap_or("Unknown"),
2183 props
2184 .description
2185 .as_deref()
2186 .unwrap_or("No description available"),
2187 props
2188 .instruction
2189 .as_deref()
2190 .unwrap_or("No specific instructions provided")
2191 )
2192}
2193 
2194fn format_period(period: &ForecastPeriod) -> String {
2195 format!(
2196 "{}:\nTemperature: {}°{}\nWind: {} {}\nForecast: {}",
2197 period.name,
2198 period.temperature,
2199 period.temperature_unit,
2200 period.wind_speed,
2201 period.wind_direction,
2202 period.detailed_forecast
2203 )
2204}
2205```
2206 
2207### Implementing the Weather server and tools
2208 
2209Now let's implement the main Weather server struct with the tool handlers:
2210 
2211```rust theme={null}
2212pub struct Weather {
2213 tool_router: ToolRouter<Weather>,
2214}
2215 
2216#[tool_router]
2217impl Weather {
2218 fn new() -> Self {
2219 Self {
2220 tool_router: Self::tool_router(),
3142221 }
315 }
316 ```
317 </CodeGroup>
318 
319 <Warning>
320 You may need to put the full path to the `uv` executable in the `command` field. You can get this by running `which uv` on macOS/Linux or `where uv` on Windows.
321 </Warning>
322 
323 <Note>
324 Make sure you pass in the absolute path to your server. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path.
325 </Note>
326 
327 This tells Claude for Desktop:
328 
329 1. There's an MCP server named "weather"
330 2. To launch it by running `uv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather.py`
331 
332 Save the file, and restart **Claude for Desktop**.
333 </Tab>
334 
335 <Tab title="TypeScript">
336 Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript)
337 
338 ### Prerequisite knowledge
339 
340 This quickstart assumes you have familiarity with:
341 
342 * TypeScript
343 * LLMs like Claude
344 
345 ### Logging in MCP Servers
346 
347 When implementing MCP servers, be careful about how you handle logging:
348 
349 **For STDIO-based servers:** Never use `console.log()`, as it writes to standard output (stdout) by default. Writing to stdout will corrupt the JSON-RPC messages and break your server.
350 
351 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
352 
353 ### Best Practices
354 
355 * Use `console.error()` which writes to stderr, or use a logging library that writes to stderr or files.
356 
357 ### Quick Examples
358 
359 ```javascript theme={null}
360 // ❌ Bad (STDIO)
361 console.log("Server started");
362 
363 // ✅ Good (STDIO)
364 console.error("Server started"); // stderr is safe
365 ```
366 
367 ### System requirements
368 
369 For TypeScript, make sure you have the latest version of Node installed.
370 
371 ### Set up your environment
372 
373 First, let's install Node.js and npm if you haven't already. You can download them from [nodejs.org](https://nodejs.org/).
374 Verify your Node.js installation:
375 
376 ```bash theme={null}
377 node --version
378 npm --version
379 ```
380 
381 For this tutorial, you'll need Node.js version 16 or higher.
382 
383 Now, let's create and set up our project:
384 
385 <CodeGroup>
386 ```bash macOS/Linux theme={null}
387 # Create a new directory for our project
388 mkdir weather
389 cd weather
390 
391 # Initialize a new npm project
392 npm init -y
393 
394 # Install dependencies
395 npm install @modelcontextprotocol/sdk zod@3
396 npm install -D @types/node typescript
397 
398 # Create our files
399 mkdir src
400 touch src/index.ts
401 ```
402 
403 ```powershell Windows theme={null}
404 # Create a new directory for our project
405 md weather
406 cd weather
407 
408 # Initialize a new npm project
409 npm init -y
410 
411 # Install dependencies
412 npm install @modelcontextprotocol/sdk zod@3
413 npm install -D @types/node typescript
414 
415 # Create our files
416 md src
417 new-item src\index.ts
418 ```
419 </CodeGroup>
420 
421 Update your package.json to add type: "module" and a build script:
422 
423 ```json package.json theme={null}
424 {
425 "type": "module",
426 "bin": {
427 "weather": "./build/index.js"
428 },
429 "scripts": {
430 "build": "tsc && chmod 755 build/index.js"
431 },
432 "files": ["build"]
433 }
434 ```
435 
436 Create a `tsconfig.json` in the root of your project:
437 
438 ```json tsconfig.json theme={null}
439 {
440 "compilerOptions": {
441 "target": "ES2022",
442 "module": "Node16",
443 "moduleResolution": "Node16",
444 "outDir": "./build",
445 "rootDir": "./src",
446 "strict": true,
447 "esModuleInterop": true,
448 "skipLibCheck": true,
449 "forceConsistentCasingInFileNames": true
450 },
451 "include": ["src/**/*"],
452 "exclude": ["node_modules"]
453 }
454 ```
455 
456 Now let's dive into building your server.
457 
458 ## Building your server
459 
460 ### Importing packages and setting up the instance
461 
462 Add these to the top of your `src/index.ts`:
463 
464 ```typescript theme={null}
465 import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
466 import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
467 import { z } from "zod";
468 
469 const NWS_API_BASE = "https://api.weather.gov";
470 const USER_AGENT = "weather-app/1.0";
471 
472 // Create server instance
473 const server = new McpServer({
474 name: "weather",
475 version: "1.0.0",
476 });
477 ```
478 
479 ### Helper functions
480 
481 Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
482 
483 ```typescript theme={null}
484 // Helper function for making NWS API requests
485 async function makeNWSRequest<T>(url: string): Promise<T | null> {
486 const headers = {
487 "User-Agent": USER_AGENT,
488 Accept: "application/geo+json",
489 };
490 
491 try {
492 const response = await fetch(url, { headers });
493 if (!response.ok) {
494 throw new Error(`HTTP error! status: ${response.status}`);
2222 }
2223 
2224 #[tool(description = "Get weather alerts for a US state.")]
2225 async fn get_alerts(
2226 &self,
2227 Parameters(MCPAlertRequest { state }): Parameters<MCPAlertRequest>,
2228 ) -> String {
2229 let url = format!(
2230 "{}/alerts/active/area/{}",
2231 NWS_API_BASE,
2232 state.to_uppercase()
2233 );
2234 
2235 match make_nws_request::<AlertsResponse>(&url).await {
2236 Ok(data) => {
2237 if data.features.is_empty() {
2238 "No active alerts for this state.".to_string()
2239 } else {
2240 data.features
2241 .iter()
2242 .map(format_alert)
2243 .collect::<Vec<_>>()
2244 .join("\n---\n")
2245 }
2246 }
2247 Err(_) => "Unable to fetch alerts or no alerts found.".to_string(),
4952248 }
496 return (await response.json()) as T;
497 } catch (error) {
498 console.error("Error making NWS request:", error);
499 return null;
500 }
501 }
502 
503 interface AlertFeature {
504 properties: {
505 event?: string;
506 areaDesc?: string;
507 severity?: string;
508 status?: string;
509 headline?: string;
510 };
511 }
512 
513 // Format alert data
514 function formatAlert(feature: AlertFeature): string {
515 const props = feature.properties;
516 return [
517 `Event: ${props.event || "Unknown"}`,
518 `Area: ${props.areaDesc || "Unknown"}`,
519 `Severity: ${props.severity || "Unknown"}`,
520 `Status: ${props.status || "Unknown"}`,
521 `Headline: ${props.headline || "No headline"}`,
522 "---",
523 ].join("\n");
524 }
525 
526 interface ForecastPeriod {
527 name?: string;
528 temperature?: number;
529 temperatureUnit?: string;
530 windSpeed?: string;
531 windDirection?: string;
532 shortForecast?: string;
533 }
534 
535 interface AlertsResponse {
536 features: AlertFeature[];
537 }
538 
539 interface PointsResponse {
540 properties: {
541 forecast?: string;
542 };
543 }
544 
545 interface ForecastResponse {
546 properties: {
547 periods: ForecastPeriod[];
548 };
549 }
550 ```
551 
552 ### Implementing tool execution
553 
554 The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
555 
556 ```typescript theme={null}
557 // Register weather tools
558 
559 server.registerTool(
560 "get_alerts",
561 {
562 description: "Get weather alerts for a state",
563 inputSchema: {
564 state: z
565 .string()
566 .length(2)
567 .describe("Two-letter state code (e.g. CA, NY)"),
568 },
569 },
570 async ({ state }) => {
571 const stateCode = state.toUpperCase();
572 const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`;
573 const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl);
574 
575 if (!alertsData) {
576 return {
577 content: [
578 {
579 type: "text",
580 text: "Failed to retrieve alerts data",
581 },
582 ],
583 };
2249 }
2250 
2251 #[tool(description = "Get weather forecast for a location.")]
2252 async fn get_forecast(
2253 &self,
2254 Parameters(MCPForecastRequest {
2255 latitude,
2256 longitude,
2257 }): Parameters<MCPForecastRequest>,
2258 ) -> String {
2259 let points_url = format!("{NWS_API_BASE}/points/{latitude},{longitude}");
2260 let Ok(points_data) = make_nws_request::<PointsResponse>(&points_url).await else {
2261 return "Unable to fetch forecast data for this location.".to_string();
2262 };
2263 
2264 let forecast_url = points_data.properties.forecast;
2265 
2266 let Ok(forecast_data) = make_nws_request::<ForecastResponse>(&forecast_url).await else {
2267 return "Unable to fetch forecast data for this location.".to_string();
2268 };
2269 
2270 let periods = &forecast_data.properties.periods;
2271 let forecast_summary: String = periods
2272 .iter()
2273 .take(5) // Next 5 periods only
2274 .map(format_period)
2275 .collect::<Vec<String>>()
2276 .join("\n---\n");
2277 forecast_summary
2278 }
2279}
2280```
2281 
2282The `#[tool_router]` macro automatically generates the routing logic, and the `#[tool]` attribute marks methods as MCP tools.
2283 
2284### Implementing the ServerHandler
2285 
2286Implement the `ServerHandler` trait to define server capabilities:
2287 
2288```rust theme={null}
2289#[tool_handler]
2290impl ServerHandler for Weather {
2291 fn get_info(&self) -> ServerInfo {
2292 ServerInfo {
2293 capabilities: ServerCapabilities::builder().enable_tools().build(),
2294 ..Default::default()
5842295 }
585 
586 const features = alertsData.features || [];
587 if (!features.length) {
588 return {
589 content: [
590 {
591 type: "text",
592 text: `No active alerts for ${stateCode}`,
593 },
594 ],
595 };
596 }
597 
598 const formattedAlerts = features.map(formatAlert);
599 const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join("\n")}`;
600 
601 return {
602 content: [
603 {
604 type: "text",
605 text: alertsText,
606 },
607 ],
608 };
609 },
610 );
611 
612 server.registerTool(
613 "get_forecast",
614 {
615 description: "Get weather forecast for a location",
616 inputSchema: {
617 latitude: z
618 .number()
619 .min(-90)
620 .max(90)
621 .describe("Latitude of the location"),
622 longitude: z
623 .number()
624 .min(-180)
625 .max(180)
626 .describe("Longitude of the location"),
627 },
628 },
629 async ({ latitude, longitude }) => {
630 // Get grid point data
631 const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`;
632 const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl);
633 
634 if (!pointsData) {
635 return {
636 content: [
637 {
638 type: "text",
639 text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`,
640 },
641 ],
642 };
643 }
644 
645 const forecastUrl = pointsData.properties?.forecast;
646 if (!forecastUrl) {
647 return {
648 content: [
649 {
650 type: "text",
651 text: "Failed to get forecast URL from grid point data",
652 },
653 ],
654 };
655 }
656 
657 // Get forecast data
658 const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl);
659 if (!forecastData) {
660 return {
661 content: [
662 {
663 type: "text",
664 text: "Failed to retrieve forecast data",
665 },
666 ],
667 };
668 }
669 
670 const periods = forecastData.properties?.periods || [];
671 if (periods.length === 0) {
672 return {
673 content: [
674 {
675 type: "text",
676 text: "No forecast periods available",
677 },
678 ],
679 };
680 }
681 
682 // Format forecast periods
683 const formattedForecast = periods.map((period: ForecastPeriod) =>
684 [
685 `${period.name || "Unknown"}:`,
686 `Temperature: ${period.temperature || "Unknown"}°${period.temperatureUnit || "F"}`,
687 `Wind: ${period.windSpeed || "Unknown"} ${period.windDirection || ""}`,
688 `${period.shortForecast || "No forecast available"}`,
689 "---",
690 ].join("\n"),
691 );
692 
693 const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join("\n")}`;
694 
695 return {
696 content: [
697 {
698 type: "text",
699 text: forecastText,
700 },
701 ],
702 };
703 },
704 );
705 ```
706 
707 ### Running the server
708 
709 Finally, implement the main function to run the server:
710 
711 ```typescript theme={null}
712 async function main() {
713 const transport = new StdioServerTransport();
714 await server.connect(transport);
715 console.error("Weather MCP Server running on stdio");
716 }
717 
718 main().catch((error) => {
719 console.error("Fatal error in main():", error);
720 process.exit(1);
721 });
722 ```
723 
724 Make sure to run `npm run build` to build your server! This is a very important step in getting your server to connect.
725 
726 Let's now test your server from an existing MCP host, Claude for Desktop.
727 
728 ## Testing your server with Claude for Desktop
729 
730 <Note>
731 Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/docs/2025-11-25/develop/build-client) tutorial to build an MCP client that connects to the server we just built.
732 </Note>
733 
734 First, make sure you have Claude for Desktop installed. [You can install the latest version
735 here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
736 
737 We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
738 
739 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
740 
741 <CodeGroup>
742 ```bash macOS/Linux theme={null}
743 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
744 ```
745 
746 ```powershell Windows theme={null}
747 code $env:AppData\Claude\claude_desktop_config.json
748 ```
749 </CodeGroup>
750 
751 You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
752 
753 In this case, we'll add our single weather server like so:
754 
755 <CodeGroup>
756 ```json macOS/Linux theme={null}
757 {
758 "mcpServers": {
759 "weather": {
760 "command": "node",
761 "args": ["/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js"]
762 }
763 }
764 }
765 ```
766 
767 ```json Windows theme={null}
768 {
769 "mcpServers": {
770 "weather": {
771 "command": "node",
772 "args": ["C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\index.js"]
773 }
774 }
775 }
776 ```
777 </CodeGroup>
778 
779 This tells Claude for Desktop:
780 
781 1. There's an MCP server named "weather"
782 2. Launch it by running `node /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js`
783 
784 Save the file, and restart **Claude for Desktop**.
785 </Tab>
786 
787 <Tab title="Java">
788 <Note>
789 This is a quickstart demo based on Spring AI MCP auto-configuration and boot starters.
790 To learn how to create sync and async MCP Servers, manually, consult the [Java SDK Server](https://java.sdk.modelcontextprotocol.io/) documentation.
791 </Note>
792 
793 Let's get started with building our weather server!
794 [You can find the complete code for what we'll be building here.](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-stdio-server)
795 
796 For more information, see the [MCP Server Boot Starter](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html) reference documentation.
797 For manual MCP Server implementation, refer to the [MCP Server Java SDK documentation](https://java.sdk.modelcontextprotocol.io/).
798 
799 ### Logging in MCP Servers
800 
801 When implementing MCP servers, be careful about how you handle logging:
802 
803 **For STDIO-based servers:** Never use `System.out.println()` or `System.out.print()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
804 
805 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
806 
807 ### Best Practices
808 
809 * Use a logging library that writes to stderr or files.
810 * Ensure any configured logging library will not write to stdout.
811 
812 ### System requirements
813 
814 * Java 17 or higher installed.
815 * [Spring Boot 3.3.x](https://docs.spring.io/spring-boot/installing.html) or higher
816 
817 ### Set up your environment
818 
819 Use the [Spring Initializer](https://start.spring.io/) to bootstrap the project.
820 
821 You will need to add the following dependencies:
822 
823 <CodeGroup>
824 ```xml Maven theme={null}
825 <dependencies>
826 <dependency>
827 <groupId>org.springframework.ai</groupId>
828 <artifactId>spring-ai-starter-mcp-server</artifactId>
829 </dependency>
830 
831 <dependency>
832 <groupId>org.springframework</groupId>
833 <artifactId>spring-web</artifactId>
834 </dependency>
835 </dependencies>
836 ```
837 
838 ```groovy Gradle theme={null}
839 dependencies {
840 implementation platform("org.springframework.ai:spring-ai-starter-mcp-server")
841 implementation platform("org.springframework:spring-web")
842 }
843 ```
844 </CodeGroup>
845 
846 Then configure your application by setting the application properties:
847 
848 <CodeGroup>
849 ```bash application.properties theme={null}
850 spring.main.bannerMode=off
851 logging.pattern.console=
852 ```
853 
854 ```yaml application.yml theme={null}
855 logging:
856 pattern:
857 console:
858 spring:
859 main:
860 banner-mode: off
861 ```
862 </CodeGroup>
863 
864 The [Server Configuration Properties](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html#_configuration_properties) documents all available properties.
865 
866 Now let's dive into building your server.
867 
868 ## Building your server
869 
870 ### Weather Service
871 
872 Let's implement a [WeatherService.java](https://github.com/spring-projects/spring-ai-examples/blob/main/model-context-protocol/weather/starter-stdio-server/src/main/java/org/springframework/ai/mcp/sample/server/WeatherService.java) that uses a REST client to query the data from the National Weather Service API:
873 
874 ```java theme={null}
875 @Service
876 public class WeatherService {
877 
878 private final RestClient restClient;
879 
880 public WeatherService() {
881 this.restClient = RestClient.builder()
882 .baseUrl("https://api.weather.gov")
883 .defaultHeader("Accept", "application/geo+json")
884 .defaultHeader("User-Agent", "WeatherApiClient/1.0 ([email protected])")
885 .build();
886 }
887 
888 @Tool(description = "Get weather forecast for a specific latitude/longitude")
889 public String getWeatherForecastByLocation(
890 double latitude, // Latitude coordinate
891 double longitude // Longitude coordinate
892 ) {
893 // Returns detailed forecast including:
894 // - Temperature and unit
895 // - Wind speed and direction
896 // - Detailed forecast description
897 }
898 
899 @Tool(description = "Get weather alerts for a US state")
900 public String getAlerts(
901 @ToolParam(description = "Two-letter US state code (e.g. CA, NY)") String state
902 ) {
903 // Returns active alerts including:
904 // - Event type
905 // - Affected area
906 // - Severity
907 // - Description
908 // - Safety instructions
909 }
910 
911 // ......
912 }
913 ```
914 
915 The `@Service` annotation will auto-register the service in your application context.
916 The Spring AI `@Tool` annotation makes it easy to create and maintain MCP tools.
917 
918 The auto-configuration will automatically register these tools with the MCP server.
919 
920 ### Create your Boot Application
921 
922 ```java theme={null}
923 @SpringBootApplication
924 public class McpServerApplication {
925 
926 public static void main(String[] args) {
927 SpringApplication.run(McpServerApplication.class, args);
928 }
929 
930 @Bean
931 public ToolCallbackProvider weatherTools(WeatherService weatherService) {
932 return MethodToolCallbackProvider.builder().toolObjects(weatherService).build();
933 }
934 }
935 ```
936 
937 Uses the `MethodToolCallbackProvider` utils to convert the `@Tools` into actionable callbacks used by the MCP server.
938 
939 ### Running the server
940 
941 Finally, let's build the server:
942 
943 ```bash theme={null}
944 ./mvnw clean install
945 ```
946 
947 This will generate an `mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar` file within the `target` folder.
948 
949 Let's now test your server from an existing MCP host, Claude for Desktop.
950 
951 ## Testing your server with Claude for Desktop
952 
953 <Note>
954 Claude for Desktop is not yet available on Linux.
955 </Note>
956 
957 First, make sure you have Claude for Desktop installed.
958 [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
959 
960 We'll need to configure Claude for Desktop for whichever MCP servers you want to use.
961 To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor.
962 Make sure to create the file if it doesn't exist.
963 
964 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
965 
966 <CodeGroup>
967 ```bash macOS/Linux theme={null}
968 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
969 ```
970 
971 ```powershell Windows theme={null}
972 code $env:AppData\Claude\claude_desktop_config.json
973 ```
974 </CodeGroup>
975 
976 You'll then add your servers in the `mcpServers` key.
977 The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
978 
979 In this case, we'll add our single weather server like so:
980 
981 <CodeGroup>
982 ```json macOS/Linux theme={null}
983 {
984 "mcpServers": {
985 "spring-ai-mcp-weather": {
986 "command": "java",
987 "args": [
988 "-Dspring.ai.mcp.server.stdio=true",
989 "-jar",
990 "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
991 ]
992 }
993 }
994 }
995 ```
996 
997 ```json Windows theme={null}
998 {
999 "mcpServers": {
1000 "spring-ai-mcp-weather": {
1001 "command": "java",
1002 "args": [
1003 "-Dspring.ai.mcp.server.transport=STDIO",
1004 "-jar",
1005 "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
1006 ]
1007 }
1008 }
1009 }
1010 ```
1011 </CodeGroup>
1012 
1013 <Note>
1014 Make sure you pass in the absolute path to your server.
1015 </Note>
1016 
1017 This tells Claude for Desktop:
1018 
1019 1. There's an MCP server named "my-weather-server"
1020 2. To launch it by running `java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar`
1021 
1022 Save the file, and restart **Claude for Desktop**.
1023 
1024 ## Testing your server with Java client
1025 
1026 ### Create an MCP Client manually
1027 
1028 Use the `McpClient` to connect to the server:
1029 
1030 ```java theme={null}
1031 var stdioParams = ServerParameters.builder("java")
1032 .args("-jar", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar")
1033 .build();
1034 
1035 var stdioTransport = new StdioClientTransport(stdioParams);
1036 
1037 var mcpClient = McpClient.sync(stdioTransport).build();
1038 
1039 mcpClient.initialize();
1040 
1041 ListToolsResult toolsList = mcpClient.listTools();
1042 
1043 CallToolResult weather = mcpClient.callTool(
1044 new CallToolRequest("getWeatherForecastByLocation",
1045 Map.of("latitude", "47.6062", "longitude", "-122.3321")));
1046 
1047 CallToolResult alert = mcpClient.callTool(
1048 new CallToolRequest("getAlerts", Map.of("state", "NY")));
1049 
1050 mcpClient.closeGracefully();
1051 ```
1052 
1053 ### Use MCP Client Boot Starter
1054 
1055 Create a new boot starter application using the `spring-ai-starter-mcp-client` dependency:
1056 
1057 ```xml theme={null}
1058 <dependency>
1059 <groupId>org.springframework.ai</groupId>
1060 <artifactId>spring-ai-starter-mcp-client</artifactId>
1061 </dependency>
1062 ```
1063 
1064 and set the `spring.ai.mcp.client.stdio.servers-configuration` property to point to your `claude_desktop_config.json`.
1065 You can reuse the existing Anthropic Desktop configuration:
1066 
1067 ```properties theme={null}
1068 spring.ai.mcp.client.stdio.servers-configuration=file:PATH/TO/claude_desktop_config.json
1069 ```
1070 
1071 When you start your client application, the auto-configuration will automatically create MCP clients from the claude\_desktop\_config.json.
1072 
1073 For more information, see the [MCP Client Boot Starters](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-client-boot-starter-docs.html) reference documentation.
1074 
1075 ## More Java MCP Server examples
1076 
1077 The [starter-webflux-server](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-webflux-server) demonstrates how to create an MCP server using SSE transport.
1078 It showcases how to define and register MCP Tools, Resources, and Prompts, using the Spring Boot's auto-configuration capabilities.
1079 </Tab>
1080 
1081 <Tab title="Kotlin">
1082 Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/weather-stdio-server)
1083 
1084 ### Prerequisite knowledge
1085 
1086 This quickstart assumes you have familiarity with:
1087 
1088 * Kotlin
1089 * LLMs like Claude
1090 
1091 ### Logging in MCP Servers
1092 
1093 When implementing MCP servers, be careful about how you handle logging:
1094 
1095 **For STDIO-based servers:** Never use `println()`, as it writes to standard output (stdout) by default. Writing to stdout will corrupt the JSON-RPC messages and break your server.
1096 
1097 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
1098 
1099 ### Best Practices
1100 
1101 * Use a logging library that writes to stderr or files.
1102 
1103 ### System requirements
1104 
1105 * JDK 11 or higher installed.
1106 
1107 ### Set up your environment
1108 
1109 First, let's install `java` and `gradle` if you haven't already.
1110 You can download `java` from [official Oracle JDK website](https://www.oracle.com/java/technologies/downloads/).
1111 Verify your `java` installation:
1112 
1113 ```bash theme={null}
1114 java --version
1115 ```
1116 
1117 Now, let's create and set up your project:
1118 
1119 <CodeGroup>
1120 ```bash macOS/Linux theme={null}
1121 # Create a new directory for our project
1122 mkdir weather
1123 cd weather
1124 
1125 # Initialize a new kotlin project
1126 gradle init
1127 ```
1128 
1129 ```powershell Windows theme={null}
1130 # Create a new directory for our project
1131 md weather
1132 cd weather
1133 
1134 # Initialize a new kotlin project
1135 gradle init
1136 ```
1137 </CodeGroup>
1138 
1139 After running `gradle init`, select **Application** as the project type, **Kotlin** as the programming language.
1140 
1141 Alternatively, you can create a Kotlin application using the [IntelliJ IDEA project wizard](https://kotlinlang.org/docs/jvm-get-started.html).
1142 
1143 After creating the project, replace the contents of your `build.gradle.kts` with:
1144 
1145 ```kotlin build.gradle.kts theme={null}
1146 // Check latest versions at https://github.com/modelcontextprotocol/kotlin-sdk/releases
1147 val mcpVersion = "0.9.0"
1148 val ktorVersion = "3.2.3"
1149 val slf4jVersion = "2.0.17"
1150 
1151 plugins {
1152 kotlin("jvm") version "2.3.20"
1153 kotlin("plugin.serialization") version "2.3.20"
1154 id("com.gradleup.shadow") version "8.3.9"
1155 application
1156 }
1157 
1158 application {
1159 mainClass.set("MainKt")
1160 }
1161 
1162 dependencies {
1163 implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion")
1164 implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion")
1165 implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")
1166 implementation("io.ktor:ktor-client-cio:$ktorVersion")
1167 implementation("org.slf4j:slf4j-simple:$slf4jVersion")
1168 }
1169 ```
1170 
1171 Verify that everything is set up correctly:
1172 
1173 ```bash theme={null}
1174 ./gradlew build
1175 ```
1176 
1177 Now let's dive into building your server.
1178 
1179 ## Building your server
1180 
1181 ### Setting up the instance
1182 
1183 Add a server initialization function:
1184 
1185 ```kotlin theme={null}
1186 fun runMcpServer() {
1187 val server = Server(
1188 Implementation(
1189 name = "weather",
1190 version = "1.0.0",
1191 ),
1192 ServerOptions(
1193 capabilities = ServerCapabilities(tools = ServerCapabilities.Tools(listChanged = true)),
1194 ),
1195 )
1196 
1197 // register tools on server here
1198 
1199 val transport = StdioServerTransport(
1200 System.`in`.asInput(),
1201 System.out.asSink().buffered(),
1202 )
1203 
1204 runBlocking {
1205 val session = server.createSession(transport)
1206 val done = Job()
1207 session.onClose {
1208 done.complete()
1209 }
1210 done.join()
1211 }
1212 }
1213 ```
1214 
1215 ### Weather API helper functions
1216 
1217 Next, let's add functions and data classes for querying and converting responses from the National Weather Service API:
1218 
1219 ```kotlin theme={null}
1220 val httpClient = HttpClient(CIO) {
1221 defaultRequest {
1222 url("https://api.weather.gov")
1223 headers {
1224 append("Accept", "application/geo+json")
1225 append("User-Agent", "WeatherApiClient/1.0")
1226 }
1227 contentType(ContentType.Application.Json)
1228 }
1229 install(ContentNegotiation) {
1230 json(Json { ignoreUnknownKeys = true })
1231 }
1232 }
1233 
1234 // Extension function to fetch weather alerts for a given state
1235 suspend fun HttpClient.getAlerts(state: String): List<String> {
1236 val alerts = this.get("/alerts/active/area/$state").body<AlertsResponse>()
1237 return alerts.features.map { feature ->
1238 """
1239 Event: ${feature.properties.event}
1240 Area: ${feature.properties.areaDesc}
1241 Severity: ${feature.properties.severity}
1242 Status: ${feature.properties.status}
1243 Headline: ${feature.properties.headline}
1244 """.trimIndent()
1245 }
1246 }
1247 
1248 // Extension function to fetch forecast information for given latitude and longitude
1249 suspend fun HttpClient.getForecast(latitude: Double, longitude: Double): List<String> {
1250 val points = this.get("/points/$latitude,$longitude").body<PointsResponse>()
1251 val forecastUrl = points.properties.forecast ?: error("No forecast URL available")
1252 val forecast = this.get(forecastUrl).body<ForecastResponse>()
1253 return forecast.properties.periods.map { period ->
1254 """
1255 ${period.name}:
1256 Temperature: ${period.temperature}°${period.temperatureUnit}
1257 Wind: ${period.windSpeed} ${period.windDirection}
1258 ${period.shortForecast}
1259 """.trimIndent()
1260 }
1261 }
1262 
1263 @Serializable
1264 data class PointsResponse(val properties: PointsProperties)
1265 
1266 @Serializable
1267 data class PointsProperties(val forecast: String? = null)
1268 
1269 @Serializable
1270 data class ForecastResponse(val properties: ForecastProperties)
1271 
1272 @Serializable
1273 data class ForecastProperties(val periods: List<ForecastPeriod> = emptyList())
1274 
1275 @Serializable
1276 data class ForecastPeriod(
1277 val name: String? = null,
1278 val temperature: Int? = null,
1279 val temperatureUnit: String? = null,
1280 val windSpeed: String? = null,
1281 val windDirection: String? = null,
1282 val shortForecast: String? = null,
1283 )
1284 
1285 @Serializable
1286 data class AlertsResponse(val features: List<AlertFeature> = emptyList())
1287 
1288 @Serializable
1289 data class AlertFeature(val properties: AlertProperties)
1290 
1291 @Serializable
1292 data class AlertProperties(
1293 val event: String? = null,
1294 val areaDesc: String? = null,
1295 val severity: String? = null,
1296 val status: String? = null,
1297 val headline: String? = null,
1298 )
1299 ```
1300 
1301 ### Implementing tool execution
1302 
1303 The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
1304 
1305 ```kotlin theme={null}
1306 // Register weather tools
1307 
1308 server.addTool(
1309 name = "get_alerts",
1310 description = "Get weather alerts for a US state. Input is a two-letter US state code (e.g. CA, NY)",
1311 inputSchema = ToolSchema(
1312 properties = buildJsonObject {
1313 putJsonObject("state") {
1314 put("type", "string")
1315 put("description", "Two-letter US state code (e.g. CA, NY)")
1316 }
1317 },
1318 required = listOf("state"),
1319 ),
1320 ) { request ->
1321 val state = request.arguments?.get("state")?.jsonPrimitive?.content
1322 ?: return@addTool CallToolResult(
1323 content = listOf(TextContent("The 'state' parameter is required.")),
1324 )
1325 
1326 val alerts = httpClient.getAlerts(state)
1327 CallToolResult(content = alerts.map { TextContent(it) })
1328 }
1329 
1330 server.addTool(
1331 name = "get_forecast",
1332 description = "Get weather forecast for a location. Note: only US locations are supported by the NWS API.",
1333 inputSchema = ToolSchema(
1334 properties = buildJsonObject {
1335 putJsonObject("latitude") {
1336 put("type", "number")
1337 put("description", "Latitude of the location")
1338 }
1339 putJsonObject("longitude") {
1340 put("type", "number")
1341 put("description", "Longitude of the location")
1342 }
1343 },
1344 required = listOf("latitude", "longitude"),
1345 ),
1346 ) { request ->
1347 val latitude = request.arguments?.get("latitude")?.jsonPrimitive?.doubleOrNull
1348 val longitude = request.arguments?.get("longitude")?.jsonPrimitive?.doubleOrNull
1349 if (latitude == null || longitude == null) {
1350 return@addTool CallToolResult(
1351 content = listOf(TextContent("The 'latitude' and 'longitude' parameters are required.")),
1352 )
1353 }
1354 
1355 val forecast = httpClient.getForecast(latitude, longitude)
1356 CallToolResult(content = forecast.map { TextContent(it) })
1357 }
1358 ```
1359 
1360 ### Running the server
1361 
1362 Finally, implement the main function to run the server:
1363 
1364 ```kotlin theme={null}
1365 fun main() = runMcpServer()
1366 ```
1367 
1368 You can run the server directly during development:
1369 
1370 ```bash theme={null}
1371 ./gradlew run
1372 ```
1373 
1374 For production use, build the shadow JAR:
1375 
1376 ```bash theme={null}
1377 ./gradlew build
1378 java -jar build/libs/weather-0.1.0-all.jar
1379 ```
1380 
1381 Let's now test your server from an existing MCP host, Claude for Desktop.
1382 
1383 ## Testing your server with Claude for Desktop
1384 
1385 <Note>
1386 Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/docs/2025-11-25/develop/build-client) tutorial to build an MCP client that connects to the server we just built.
1387 </Note>
1388 
1389 First, make sure you have Claude for Desktop installed. [You can install the latest version
1390 here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
1391 
1392 We'll need to configure Claude for Desktop for whichever MCP servers you want to use.
1393 To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor.
1394 Make sure to create the file if it doesn't exist.
1395 
1396 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
1397 
1398 <CodeGroup>
1399 ```bash macOS/Linux theme={null}
1400 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
1401 ```
1402 
1403 ```powershell Windows theme={null}
1404 code $env:AppData\Claude\claude_desktop_config.json
1405 ```
1406 </CodeGroup>
1407 
1408 You'll then add your servers in the `mcpServers` key.
1409 The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
1410 
1411 In this case, we'll add our single weather server like so:
1412 
1413 <CodeGroup>
1414 ```json macOS/Linux theme={null}
1415 {
1416 "mcpServers": {
1417 "weather": {
1418 "command": "java",
1419 "args": [
1420 "-jar",
1421 "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/libs/weather-0.1.0-all.jar"
1422 ]
1423 }
1424 }
1425 }
1426 ```
1427 
1428 ```json Windows theme={null}
1429 {
1430 "mcpServers": {
1431 "weather": {
1432 "command": "java",
1433 "args": [
1434 "-jar",
1435 "C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\libs\\weather-0.1.0-all.jar"
1436 ]
1437 }
1438 }
1439 }
1440 ```
1441 </CodeGroup>
1442 
1443 This tells Claude for Desktop:
1444 
1445 1. There's an MCP server named "weather"
1446 2. Launch it by running `java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/libs/weather-0.1.0-all.jar`
1447 
1448 Save the file, and restart **Claude for Desktop**.
1449 </Tab>
1450 
1451 <Tab title="C#">
1452 Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/csharp-sdk/tree/main/samples/QuickstartWeatherServer)
1453 
1454 ### Prerequisite knowledge
1455 
1456 This quickstart assumes you have familiarity with:
1457 
1458 * C#
1459 * LLMs like Claude
1460 * .NET 8 or higher
1461 
1462 ### Logging in MCP Servers
1463 
1464 When implementing MCP servers, be careful about how you handle logging:
1465 
1466 **For STDIO-based servers:** Never use `Console.WriteLine()` or `Console.Write()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
1467 
1468 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
1469 
1470 ### Best Practices
1471 
1472 * Use a logging library that writes to stderr or files.
1473 
1474 ### System requirements
1475 
1476 * [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) or higher installed.
1477 
1478 ### Set up your environment
1479 
1480 First, let's install `dotnet` if you haven't already. You can download `dotnet` from [official Microsoft .NET website](https://dotnet.microsoft.com/download/). Verify your `dotnet` installation:
1481 
1482 ```bash theme={null}
1483 dotnet --version
1484 ```
1485 
1486 Now, let's create and set up your project:
1487 
1488 <CodeGroup>
1489 ```bash macOS/Linux theme={null}
1490 # Create a new directory for our project
1491 mkdir weather
1492 cd weather
1493 # Initialize a new C# project
1494 dotnet new console
1495 ```
1496 
1497 ```powershell Windows theme={null}
1498 # Create a new directory for our project
1499 mkdir weather
1500 cd weather
1501 # Initialize a new C# project
1502 dotnet new console
1503 ```
1504 </CodeGroup>
1505 
1506 After running `dotnet new console`, you will be presented with a new C# project.
1507 You can open the project in your favorite IDE, such as [Visual Studio](https://visualstudio.microsoft.com/) or [Rider](https://www.jetbrains.com/rider/).
1508 Alternatively, you can create a C# application using the [Visual Studio project wizard](https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-console?view=vs-2022).
1509 After creating the project, add NuGet package for the Model Context Protocol SDK and hosting:
1510 
1511 ```bash theme={null}
1512 # Add the Model Context Protocol SDK NuGet package
1513 dotnet add package ModelContextProtocol --prerelease
1514 # Add the .NET Hosting NuGet package
1515 dotnet add package Microsoft.Extensions.Hosting
1516 ```
1517 
1518 Now let’s dive into building your server.
1519 
1520 ## Building your server
1521 
1522 Open the `Program.cs` file in your project and replace its contents with the following code:
1523 
1524 ```csharp theme={null}
1525 using Microsoft.Extensions.DependencyInjection;
1526 using Microsoft.Extensions.Hosting;
1527 using ModelContextProtocol;
1528 using System.Net.Http.Headers;
1529 
1530 var builder = Host.CreateEmptyApplicationBuilder(settings: null);
1531 
1532 builder.Services.AddMcpServer()
1533 .WithStdioServerTransport()
1534 .WithToolsFromAssembly();
1535 
1536 builder.Services.AddSingleton(_ =>
1537 {
1538 var client = new HttpClient() { BaseAddress = new Uri("https://api.weather.gov") };
1539 client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("weather-tool", "1.0"));
1540 return client;
1541 });
1542 
1543 var app = builder.Build();
1544 
1545 await app.RunAsync();
1546 ```
1547 
1548 <Note>
1549 When creating the `ApplicationHostBuilder`, ensure you use `CreateEmptyApplicationBuilder` instead of `CreateDefaultBuilder`. This ensures that the server does not write any additional messages to the console. This is only necessary for servers using STDIO transport.
1550 </Note>
1551 
1552 This code sets up a basic console application that uses the Model Context Protocol SDK to create an MCP server with standard I/O transport.
1553 
1554 ### Weather API helper functions
1555 
1556 Create an extension class for `HttpClient` which helps simplify JSON request handling:
1557 
1558 ```csharp theme={null}
1559 using System.Text.Json;
1560 
1561 internal static class HttpClientExt
1562 {
1563 public static async Task<JsonDocument> ReadJsonDocumentAsync(this HttpClient client, string requestUri)
1564 {
1565 using var response = await client.GetAsync(requestUri);
1566 response.EnsureSuccessStatusCode();
1567 return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
1568 }
1569 }
1570 ```
1571 
1572 Next, define a class with the tool execution handlers for querying and converting responses from the National Weather Service API:
1573 
1574 ```csharp theme={null}
1575 using ModelContextProtocol.Server;
1576 using System.ComponentModel;
1577 using System.Globalization;
1578 using System.Text.Json;
1579 
1580 namespace QuickstartWeatherServer.Tools;
1581 
1582 [McpServerToolType]
1583 public static class WeatherTools
1584 {
1585 [McpServerTool, Description("Get weather alerts for a US state code.")]
1586 public static async Task<string> GetAlerts(
1587 HttpClient client,
1588 [Description("The US state code to get alerts for.")] string state)
1589 {
1590 using var jsonDocument = await client.ReadJsonDocumentAsync($"/alerts/active/area/{state}");
1591 var jsonElement = jsonDocument.RootElement;
1592 var alerts = jsonElement.GetProperty("features").EnumerateArray();
1593 
1594 if (!alerts.Any())
1595 {
1596 return "No active alerts for this state.";
1597 }
1598 
1599 return string.Join("\n--\n", alerts.Select(alert =>
1600 {
1601 JsonElement properties = alert.GetProperty("properties");
1602 return $"""
1603 Event: {properties.GetProperty("event").GetString()}
1604 Area: {properties.GetProperty("areaDesc").GetString()}
1605 Severity: {properties.GetProperty("severity").GetString()}
1606 Description: {properties.GetProperty("description").GetString()}
1607 Instruction: {properties.GetProperty("instruction").GetString()}
1608 """;
1609 }));
1610 }
1611 
1612 [McpServerTool, Description("Get weather forecast for a location.")]
1613 public static async Task<string> GetForecast(
1614 HttpClient client,
1615 [Description("Latitude of the location.")] double latitude,
1616 [Description("Longitude of the location.")] double longitude)
1617 {
1618 var pointUrl = string.Create(CultureInfo.InvariantCulture, $"/points/{latitude},{longitude}");
1619 using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);
1620 var forecastUrl = jsonDocument.RootElement.GetProperty("properties").GetProperty("forecast").GetString()
1621 ?? throw new Exception($"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}");
1622 
1623 using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl);
1624 var periods = forecastDocument.RootElement.GetProperty("properties").GetProperty("periods").EnumerateArray();
1625 
1626 return string.Join("\n---\n", periods.Select(period => $"""
1627 {period.GetProperty("name").GetString()}
1628 Temperature: {period.GetProperty("temperature").GetInt32()}°F
1629 Wind: {period.GetProperty("windSpeed").GetString()} {period.GetProperty("windDirection").GetString()}
1630 Forecast: {period.GetProperty("detailedForecast").GetString()}
1631 """));
1632 }
1633 }
1634 ```
1635 
1636 ### Running the server
1637 
1638 Finally, run the server using the following command:
1639 
1640 ```bash theme={null}
1641 dotnet run
1642 ```
1643 
1644 This will start the server and listen for incoming requests on standard input/output.
1645 
1646 ## Testing your server with Claude for Desktop
1647 
1648 <Note>
1649 Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/docs/2025-11-25/develop/build-client) tutorial to build an MCP client that connects to the server we just built.
1650 </Note>
1651 
1652 First, make sure you have Claude for Desktop installed. [You can install the latest version
1653 here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
1654 We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
1655 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
1656 
1657 <CodeGroup>
1658 ```bash macOS/Linux theme={null}
1659 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
1660 ```
1661 
1662 ```powershell Windows theme={null}
1663 code $env:AppData\Claude\claude_desktop_config.json
1664 ```
1665 </CodeGroup>
1666 
1667 You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
1668 In this case, we'll add our single weather server like so:
1669 
1670 <CodeGroup>
1671 ```json macOS/Linux theme={null}
1672 {
1673 "mcpServers": {
1674 "weather": {
1675 "command": "dotnet",
1676 "args": ["run", "--project", "/ABSOLUTE/PATH/TO/PROJECT", "--no-build"]
1677 }
1678 }
1679 }
1680 ```
1681 
1682 ```json Windows theme={null}
1683 {
1684 "mcpServers": {
1685 "weather": {
1686 "command": "dotnet",
1687 "args": [
1688 "run",
1689 "--project",
1690 "C:\\ABSOLUTE\\PATH\\TO\\PROJECT",
1691 "--no-build"
1692 ]
1693 }
1694 }
1695 }
1696 ```
1697 </CodeGroup>
1698 
1699 This tells Claude for Desktop:
1700 
1701 1. There's an MCP server named "weather"
1702 2. Launch it by running `dotnet run /ABSOLUTE/PATH/TO/PROJECT`
1703 Save the file, and restart **Claude for Desktop**.
1704 </Tab>
1705 
1706 <Tab title="Ruby">
1707 Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-ruby)
1708 
1709 ### Prerequisite knowledge
1710 
1711 This quickstart assumes you have familiarity with:
1712 
1713 * Ruby
1714 * LLMs like Claude
1715 
1716 ### Logging in MCP Servers
1717 
1718 When implementing MCP servers, be careful about how you handle logging:
1719 
1720 **For STDIO-based servers:** Never use `puts` or `print`, as they write to standard output (stdout) by default. Writing to stdout will corrupt the JSON-RPC messages and break your server.
1721 
1722 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
1723 
1724 ### Best Practices
1725 
1726 * Use a logging library that writes to stderr or files.
1727 
1728 ### Quick Examples
1729 
1730 ```ruby theme={null}
1731 # ❌ Bad (STDIO)
1732 puts "Processing request"
1733 
1734 # ✅ Good (STDIO)
1735 require "logger"
1736 logger = Logger.new($stderr)
1737 logger.info("Processing request")
1738 ```
1739 
1740 ### System requirements
1741 
1742 * Ruby 2.7 or higher installed.
1743 
1744 ### Set up your environment
1745 
1746 First, let's make sure you have Ruby installed. You can check by running:
1747 
1748 ```bash theme={null}
1749 ruby --version
1750 ```
1751 
1752 Now, let's create and set up our project:
1753 
1754 <CodeGroup>
1755 ```bash macOS/Linux theme={null}
1756 # Create a new directory for our project
1757 mkdir weather
1758 cd weather
1759 
1760 # Create a Gemfile
1761 bundle init
1762 
1763 # Add the MCP SDK dependency
1764 bundle add mcp
1765 
1766 # Create our server file
1767 touch weather.rb
1768 ```
1769 
1770 ```powershell Windows theme={null}
1771 # Create a new directory for our project
1772 mkdir weather
1773 cd weather
1774 
1775 # Create a Gemfile
1776 bundle init
1777 
1778 # Add the MCP SDK dependency
1779 bundle add mcp
1780 
1781 # Create our server file
1782 new-item weather.rb
1783 ```
1784 </CodeGroup>
1785 
1786 Now let's dive into building your server.
1787 
1788 ## Building your server
1789 
1790 ### Importing packages and setting up constants
1791 
1792 Open `weather.rb` and add these requires and constants at the top:
1793 
1794 ```ruby theme={null}
1795 require "json"
1796 require "mcp"
1797 require "net/http"
1798 require "uri"
1799 
1800 NWS_API_BASE = "https://api.weather.gov"
1801 USER_AGENT = "weather-app/1.0"
1802 ```
1803 
1804 The `mcp` gem provides the Model Context Protocol SDK for Ruby, with classes for server implementation and stdio transport.
1805 
1806 ### Helper methods
1807 
1808 Next, let's add helper methods for querying and formatting data from the National Weather Service API:
1809 
1810 ```ruby theme={null}
1811 module HelperMethods
1812 def make_nws_request(url)
1813 uri = URI(url)
1814 request = Net::HTTP::Get.new(uri)
1815 request["User-Agent"] = USER_AGENT
1816 request["Accept"] = "application/geo+json"
1817 
1818 response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
1819 http.request(request)
1820 end
1821 
1822 raise "HTTP #{response.code}: #{response.message}" unless response.is_a?(Net::HTTPSuccess)
1823 
1824 JSON.parse(response.body)
1825 end
1826 
1827 def format_alert(feature)
1828 properties = feature["properties"]
1829 
1830 <<~ALERT
1831 Event: #{properties["event"] || "Unknown"}
1832 Area: #{properties["areaDesc"] || "Unknown"}
1833 Severity: #{properties["severity"] || "Unknown"}
1834 Description: #{properties["description"] || "No description available"}
1835 Instructions: #{properties["instruction"] || "No specific instructions provided"}
1836 ALERT
1837 end
1838 end
1839 ```
1840 
1841 ### Implementing tool execution
1842 
1843 Now let's define our tool classes. Each tool subclasses `MCP::Tool` and implements the tool logic:
1844 
1845 ```ruby theme={null}
1846 class GetAlerts < MCP::Tool
1847 extend HelperMethods
1848 
1849 tool_name "get_alerts"
1850 description "Get weather alerts for a US state"
1851 input_schema(
1852 properties: {
1853 state: {
1854 type: "string",
1855 description: "Two-letter US state code (e.g. CA, NY)"
1856 }
1857 },
1858 required: ["state"]
1859 )
1860 
1861 def self.call(state:)
1862 url = "#{NWS_API_BASE}/alerts/active/area/#{state.upcase}"
1863 data = make_nws_request(url)
1864 
1865 if data["features"].empty?
1866 return MCP::Tool::Response.new([{
1867 type: "text",
1868 text: "No active alerts for this state."
1869 }])
1870 end
1871 
1872 alerts = data["features"].map { |feature| format_alert(feature) }
1873 MCP::Tool::Response.new([{
1874 type: "text",
1875 text: alerts.join("\n---\n")
1876 }])
1877 end
1878 end
1879 
1880 class GetForecast < MCP::Tool
1881 extend HelperMethods
1882 
1883 tool_name "get_forecast"
1884 description "Get weather forecast for a location"
1885 input_schema(
1886 properties: {
1887 latitude: {
1888 type: "number",
1889 description: "Latitude of the location"
1890 },
1891 longitude: {
1892 type: "number",
1893 description: "Longitude of the location"
1894 }
1895 },
1896 required: ["latitude", "longitude"]
1897 )
1898 
1899 def self.call(latitude:, longitude:)
1900 # First get the forecast grid endpoint.
1901 points_url = "#{NWS_API_BASE}/points/#{latitude},#{longitude}"
1902 points_data = make_nws_request(points_url)
1903 
1904 # Get the forecast URL from the points response.
1905 forecast_url = points_data["properties"]["forecast"]
1906 forecast_data = make_nws_request(forecast_url)
1907 
1908 # Format the periods into a readable forecast.
1909 periods = forecast_data["properties"]["periods"]
1910 forecasts = periods.first(5).map do |period|
1911 <<~FORECAST
1912 #{period["name"]}:
1913 Temperature: #{period["temperature"]}°#{period["temperatureUnit"]}
1914 Wind: #{period["windSpeed"]} #{period["windDirection"]}
1915 Forecast: #{period["detailedForecast"]}
1916 FORECAST
1917 end
1918 
1919 MCP::Tool::Response.new([{
1920 type: "text",
1921 text: forecasts.join("\n---\n")
1922 }])
1923 end
1924 end
1925 ```
1926 
1927 ### Running the server
1928 
1929 Finally, initialize and run the server:
1930 
1931 ```ruby theme={null}
1932 server = MCP::Server.new(
1933 name: "weather",
1934 version: "1.0.0",
1935 tools: [GetAlerts, GetForecast]
1936 )
1937 
1938 transport = MCP::Server::Transports::StdioTransport.new(server)
1939 transport.open
1940 ```
1941 
1942 Your server is complete! Run `bundle exec ruby weather.rb` to start the MCP server, which will listen for messages from MCP hosts.
1943 
1944 Let's now test your server from an existing MCP host, Claude for Desktop.
1945 
1946 ## Testing your server with Claude for Desktop
1947 
1948 <Note>
1949 Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/docs/2025-11-25/develop/build-client) tutorial to build an MCP client that connects to the server we just built.
1950 </Note>
1951 
1952 First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
1953 
1954 We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
1955 
1956 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
1957 
1958 <CodeGroup>
1959 ```bash macOS/Linux theme={null}
1960 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
1961 ```
1962 
1963 ```powershell Windows theme={null}
1964 code $env:AppData\Claude\claude_desktop_config.json
1965 ```
1966 </CodeGroup>
1967 
1968 You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
1969 
1970 In this case, we'll add our single weather server like so:
1971 
1972 <CodeGroup>
1973 ```json macOS/Linux theme={null}
1974 {
1975 "mcpServers": {
1976 "weather": {
1977 "command": "bundle",
1978 "args": ["exec", "ruby", "weather.rb"],
1979 "cwd": "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather"
1980 }
1981 }
1982 }
1983 ```
1984 
1985 ```json Windows theme={null}
1986 {
1987 "mcpServers": {
1988 "weather": {
1989 "command": "bundle",
1990 "args": ["exec", "ruby", "weather.rb"],
1991 "cwd": "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather"
1992 }
1993 }
1994 }
1995 ```
1996 </CodeGroup>
1997 
1998 <Note>
1999 Make sure you pass in the absolute path to your project directory in the `cwd` field. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt from your project directory. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path.
2000 </Note>
2001 
2002 This tells Claude for Desktop:
2003 
2004 1. There's an MCP server named "weather"
2005 2. Launch it by running `bundle exec ruby weather.rb` in the specified directory
2006 
2007 Save the file, and restart **Claude for Desktop**.
2008 </Tab>
2009 
2010 <Tab title="Rust">
2011 Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-rust)
2012 
2013 ### Prerequisite knowledge
2014 
2015 This quickstart assumes you have familiarity with:
2016 
2017 * Rust programming language
2018 * Async/await in Rust
2019 * LLMs like Claude
2020 
2021 ### Logging in MCP Servers
2022 
2023 When implementing MCP servers, be careful about how you handle logging:
2024 
2025 **For STDIO-based servers:** Never use `println!()` or `print!()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
2026 
2027 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
2028 
2029 ### Best Practices
2030 
2031 * Use a logging library that writes to stderr or files, such as `tracing` or `log` in Rust.
2032 * Configure your logging framework to avoid stdout output.
2033 
2034 ### Quick Examples
2035 
2036 ```rust theme={null}
2037 // ❌ Bad (STDIO)
2038 println!("Processing request");
2039 
2040 // ✅ Good (STDIO)
2041 eprintln!("Processing request"); // writes to stderr
2042 ```
2043 
2044 ### System requirements
2045 
2046 * Rust 1.70 or higher installed.
2047 * Cargo (comes with Rust installation).
2048 
2049 ### Set up your environment
2050 
2051 First, let's install Rust if you haven't already. You can install Rust from [rust-lang.org](https://www.rust-lang.org/tools/install):
2052 
2053 <CodeGroup>
2054 ```bash macOS/Linux theme={null}
2055 curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
2056 ```
2057 
2058 ```powershell Windows theme={null}
2059 # Download and run rustup-init.exe from https://rustup.rs/
2060 ```
2061 </CodeGroup>
2062 
2063 Verify your Rust installation:
2064 
2065 ```bash theme={null}
2066 rustc --version
2067 cargo --version
2068 ```
2069 
2070 Now, let's create and set up our project:
2071 
2072 <CodeGroup>
2073 ```bash macOS/Linux theme={null}
2074 # Create a new Rust project
2075 cargo new weather
2076 cd weather
2077 ```
2078 
2079 ```powershell Windows theme={null}
2080 # Create a new Rust project
2081 cargo new weather
2082 cd weather
2083 ```
2084 </CodeGroup>
2085 
2086 Update your `Cargo.toml` to add the required dependencies:
2087 
2088 ```toml Cargo.toml theme={null}
2089 [package]
2090 name = "weather"
2091 version = "0.1.0"
2092 edition = "2024"
2093 
2094 [dependencies]
2095 rmcp = { version = "0.3", features = ["server", "macros", "transport-io"] }
2096 tokio = { version = "1.46", features = ["full"] }
2097 reqwest = { version = "0.12", features = ["json"] }
2098 serde = { version = "1.0", features = ["derive"] }
2099 serde_json = "1.0"
2100 anyhow = "1.0"
2101 tracing = "0.1"
2102 tracing-subscriber = { version = "0.3", features = ["env-filter", "std", "fmt"] }
2103 ```
2104 
2105 Now let's dive into building your server.
2106 
2107 ## Building your server
2108 
2109 ### Importing packages and constants
2110 
2111 Open `src/main.rs` and add these imports and constants at the top:
2112 
2113 ```rust theme={null}
2114 use anyhow::Result;
2115 use rmcp::{
2116 ServerHandler, ServiceExt,
2117 handler::server::{router::tool::ToolRouter, tool::Parameters},
2118 model::*,
2119 schemars, tool, tool_handler, tool_router,
2120 };
2121 use serde::Deserialize;
2122 use serde::de::DeserializeOwned;
2123 
2124 const NWS_API_BASE: &str = "https://api.weather.gov";
2125 const USER_AGENT: &str = "weather-app/1.0";
2126 ```
2127 
2128 The `rmcp` crate provides the Model Context Protocol SDK for Rust, with features for server implementation, procedural macros, and stdio transport.
2129 
2130 ### Data structures
2131 
2132 Next, let's define the data structures for deserializing responses from the National Weather Service API:
2133 
2134 ```rust theme={null}
2135 #[derive(Debug, Deserialize)]
2136 struct AlertsResponse {
2137 features: Vec<AlertFeature>,
2138 }
2139 
2140 #[derive(Debug, Deserialize)]
2141 struct AlertFeature {
2142 properties: AlertProperties,
2143 }
2144 
2145 #[derive(Debug, Deserialize)]
2146 struct AlertProperties {
2147 event: Option<String>,
2148 #[serde(rename = "areaDesc")]
2149 area_desc: Option<String>,
2150 severity: Option<String>,
2151 description: Option<String>,
2152 instruction: Option<String>,
2153 }
2154 
2155 #[derive(Debug, Deserialize)]
2156 struct PointsResponse {
2157 properties: PointsProperties,
2158 }
2159 
2160 #[derive(Debug, Deserialize)]
2161 struct PointsProperties {
2162 forecast: String,
2163 }
2164 
2165 #[derive(Debug, Deserialize)]
2166 struct ForecastResponse {
2167 properties: ForecastProperties,
2168 }
2169 
2170 #[derive(Debug, Deserialize)]
2171 struct ForecastProperties {
2172 periods: Vec<ForecastPeriod>,
2173 }
2174 
2175 #[derive(Debug, Deserialize)]
2176 struct ForecastPeriod {
2177 name: String,
2178 temperature: i32,
2179 #[serde(rename = "temperatureUnit")]
2180 temperature_unit: String,
2181 #[serde(rename = "windSpeed")]
2182 wind_speed: String,
2183 #[serde(rename = "windDirection")]
2184 wind_direction: String,
2185 #[serde(rename = "detailedForecast")]
2186 detailed_forecast: String,
2187 }
2188 ```
2189 
2190 Now define the request types that MCP clients will send:
2191 
2192 ```rust theme={null}
2193 #[derive(serde::Deserialize, schemars::JsonSchema)]
2194 pub struct MCPForecastRequest {
2195 latitude: f32,
2196 longitude: f32,
2197 }
2198 
2199 #[derive(serde::Deserialize, schemars::JsonSchema)]
2200 pub struct MCPAlertRequest {
2201 state: String,
2202 }
2203 ```
2204 
2205 ### Helper functions
2206 
2207 Add helper functions for making API requests and formatting responses:
2208 
2209 ```rust theme={null}
2210 async fn make_nws_request<T: DeserializeOwned>(url: &str) -> Result<T> {
2211 let client = reqwest::Client::new();
2212 let rsp = client
2213 .get(url)
2214 .header(reqwest::header::USER_AGENT, USER_AGENT)
2215 .header(reqwest::header::ACCEPT, "application/geo+json")
2216 .send()
2217 .await?
2218 .error_for_status()?;
2219 Ok(rsp.json::<T>().await?)
2220 }
2221 
2222 fn format_alert(feature: &AlertFeature) -> String {
2223 let props = &feature.properties;
2224 format!(
2225 "Event: {}\nArea: {}\nSeverity: {}\nDescription: {}\nInstructions: {}",
2226 props.event.as_deref().unwrap_or("Unknown"),
2227 props.area_desc.as_deref().unwrap_or("Unknown"),
2228 props.severity.as_deref().unwrap_or("Unknown"),
2229 props
2230 .description
2231 .as_deref()
2232 .unwrap_or("No description available"),
2233 props
2234 .instruction
2235 .as_deref()
2236 .unwrap_or("No specific instructions provided")
2237 )
2238 }
2239 
2240 fn format_period(period: &ForecastPeriod) -> String {
2241 format!(
2242 "{}:\nTemperature: {}°{}\nWind: {} {}\nForecast: {}",
2243 period.name,
2244 period.temperature,
2245 period.temperature_unit,
2246 period.wind_speed,
2247 period.wind_direction,
2248 period.detailed_forecast
2249 )
2250 }
2251 ```
2252 
2253 ### Implementing the Weather server and tools
2254 
2255 Now let's implement the main Weather server struct with the tool handlers:
2256 
2257 ```rust theme={null}
2258 pub struct Weather {
2259 tool_router: ToolRouter<Weather>,
2260 }
2261 
2262 #[tool_router]
2263 impl Weather {
2264 fn new() -> Self {
2265 Self {
2266 tool_router: Self::tool_router(),
2267 }
2268 }
2269 
2270 #[tool(description = "Get weather alerts for a US state.")]
2271 async fn get_alerts(
2272 &self,
2273 Parameters(MCPAlertRequest { state }): Parameters<MCPAlertRequest>,
2274 ) -> String {
2275 let url = format!(
2276 "{}/alerts/active/area/{}",
2277 NWS_API_BASE,
2278 state.to_uppercase()
2279 );
2280 
2281 match make_nws_request::<AlertsResponse>(&url).await {
2282 Ok(data) => {
2283 if data.features.is_empty() {
2284 "No active alerts for this state.".to_string()
2285 } else {
2286 data.features
2287 .iter()
2288 .map(format_alert)
2289 .collect::<Vec<_>>()
2290 .join("\n---\n")
2291 }
2292 }
2293 Err(_) => "Unable to fetch alerts or no alerts found.".to_string(),
2294 }
2295 }
2296 
2297 #[tool(description = "Get weather forecast for a location.")]
2298 async fn get_forecast(
2299 &self,
2300 Parameters(MCPForecastRequest {
2301 latitude,
2302 longitude,
2303 }): Parameters<MCPForecastRequest>,
2304 ) -> String {
2305 let points_url = format!("{NWS_API_BASE}/points/{latitude},{longitude}");
2306 let Ok(points_data) = make_nws_request::<PointsResponse>(&points_url).await else {
2307 return "Unable to fetch forecast data for this location.".to_string();
2308 };
2309 
2310 let forecast_url = points_data.properties.forecast;
2311 
2312 let Ok(forecast_data) = make_nws_request::<ForecastResponse>(&forecast_url).await else {
2313 return "Unable to fetch forecast data for this location.".to_string();
2314 };
2315 
2316 let periods = &forecast_data.properties.periods;
2317 let forecast_summary: String = periods
2318 .iter()
2319 .take(5) // Next 5 periods only
2320 .map(format_period)
2321 .collect::<Vec<String>>()
2322 .join("\n---\n");
2323 forecast_summary
2324 }
2325 }
2326 ```
2327 
2328 The `#[tool_router]` macro automatically generates the routing logic, and the `#[tool]` attribute marks methods as MCP tools.
2329 
2330 ### Implementing the ServerHandler
2331 
2332 Implement the `ServerHandler` trait to define server capabilities:
2333 
2334 ```rust theme={null}
2335 #[tool_handler]
2336 impl ServerHandler for Weather {
2337 fn get_info(&self) -> ServerInfo {
2338 ServerInfo {
2339 capabilities: ServerCapabilities::builder().enable_tools().build(),
2340 ..Default::default()
2341 }
2342 }
2343 }
2344 ```
2345 
2346 ### Running the server
2347 
2348 Finally, implement the main function to run the server with stdio transport:
2349 
2350 ```rust theme={null}
2351 #[tokio::main]
2352 async fn main() -> Result<()> {
2353 let transport = (tokio::io::stdin(), tokio::io::stdout());
2354 let service = Weather::new().serve(transport).await?;
2355 service.waiting().await?;
2356 Ok(())
2357 }
2358 ```
2359 
2360 Build your server with:
2361 
2362 ```bash theme={null}
2363 cargo build --release
2364 ```
2365 
2366 The compiled binary will be in `target/release/weather`.
2367 
2368 Let's now test your server from an existing MCP host, Claude for Desktop.
2369 
2370 ## Testing your server with Claude for Desktop
2371 
2372 <Note>
2373 Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/docs/2025-11-25/develop/build-client) tutorial to build an MCP client that connects to the server we just built.
2374 </Note>
2375 
2376 First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
2377 
2378 We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
2379 
2380 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
2381 
2382 <CodeGroup>
2383 ```bash macOS/Linux theme={null}
2384 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
2385 ```
2386 
2387 ```powershell Windows theme={null}
2388 code $env:AppData\Claude\claude_desktop_config.json
2389 ```
2390 </CodeGroup>
2391 
2392 You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
2393 
2394 In this case, we'll add our single weather server like so:
2395 
2396 <CodeGroup>
2397 ```json macOS/Linux theme={null}
2398 {
2399 "mcpServers": {
2400 "weather": {
2401 "command": "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/target/release/weather"
2402 }
2403 }
2404 }
2405 ```
2406 
2407 ```json Windows theme={null}
2408 {
2409 "mcpServers": {
2410 "weather": {
2411 "command": "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\target\\release\\weather.exe"
2412 }
2413 }
2414 }
2415 ```
2416 </CodeGroup>
2417 
2418 <Note>
2419 Make sure you pass in the absolute path to your compiled binary. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt from your project directory. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path, and add the `.exe` extension.
2420 </Note>
2421 
2422 This tells Claude for Desktop:
2423 
2424 1. There's an MCP server named "weather"
2425 2. Launch it by running the compiled binary at the specified path
2426 
2427 Save the file, and restart **Claude for Desktop**.
2428 </Tab>
2429 
2430 <Tab title="Go">
2431 Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-go)
2432 
2433 ### Prerequisite knowledge
2434 
2435 This quickstart assumes you have familiarity with:
2436 
2437 * Go
2438 * LLMs like Claude
2439 
2440 ### Logging in MCP Servers
2441 
2442 When implementing MCP servers, be careful about how you handle logging:
2443 
2444 **For STDIO-based servers:** Never use `fmt.Println()` or `fmt.Printf()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
2445 
2446 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
2447 
2448 ### Best Practices
2449 
2450 * Use `log.Println()` (which defaults to stderr) or a logging library that writes to stderr or files.
2451 * Use `fmt.Fprintf(os.Stderr, ...)` to write to stderr explicitly.
2452 
2453 ### Quick Examples
2454 
2455 ```go theme={null}
2456 // ❌ Bad (STDIO)
2457 fmt.Println("Processing request")
2458 
2459 // ✅ Good (STDIO)
2460 log.Println("Processing request") // defaults to stderr
2461 
2462 // ✅ Good (STDIO)
2463 fmt.Fprintln(os.Stderr, "Processing request")
2464 ```
2465 
2466 ### System requirements
2467 
2468 * Go 1.24 or higher installed.
2469 
2470 ### Set up your environment
2471 
2472 First, let's install Go if you haven't already. You can download and install Go from [go.dev](https://go.dev/dl/).
2473 
2474 Verify your Go installation:
2475 
2476 ```bash theme={null}
2477 go version
2478 ```
2479 
2480 Now, let's create and set up our project:
2481 
2482 <CodeGroup>
2483 ```bash macOS/Linux theme={null}
2484 # Create a new directory for our project
2485 mkdir weather
2486 cd weather
2487 
2488 # Initialize Go module
2489 go mod init weather
2490 
2491 # Install dependencies
2492 go get github.com/modelcontextprotocol/go-sdk/mcp
2493 
2494 # Create our server file
2495 touch main.go
2496 ```
2497 
2498 ```powershell Windows theme={null}
2499 # Create a new directory for our project
2500 md weather
2501 cd weather
2502 
2503 # Initialize Go module
2504 go mod init weather
2505 
2506 # Install dependencies
2507 go get github.com/modelcontextprotocol/go-sdk/mcp
2508 
2509 # Create our server file
2510 new-item main.go
2511 ```
2512 </CodeGroup>
2513 
2514 Now let's dive into building your server.
2515 
2516 ## Building your server
2517 
2518 ### Importing packages and constants
2519 
2520 Add these to the top of your `main.go`:
2521 
2522 ```go theme={null}
2523 package main
2524 
2525 import (
2526 "cmp"
2527 "context"
2528 "encoding/json"
2529 "fmt"
2530 "io"
2531 "log"
2532 "net/http"
2533 "strings"
2534 
2535 "github.com/modelcontextprotocol/go-sdk/mcp"
2536 )
2537 
2538 const (
2539 NWSAPIBase = "https://api.weather.gov"
2540 UserAgent = "weather-app/1.0"
2541 )
2542 ```
2543 
2544 ### Data structures
2545 
2546 Next, let's define the data structures used by our tools:
2547 
2548 ```go theme={null}
2549 type PointsResponse struct {
2550 Properties struct {
2551 Forecast string `json:"forecast"`
2552 } `json:"properties"`
2553 }
2554 
2555 type ForecastResponse struct {
2556 Properties struct {
2557 Periods []ForecastPeriod `json:"periods"`
2558 } `json:"properties"`
2559 }
2560 
2561 type ForecastPeriod struct {
2562 Name string `json:"name"`
2563 Temperature int `json:"temperature"`
2564 TemperatureUnit string `json:"temperatureUnit"`
2565 WindSpeed string `json:"windSpeed"`
2566 WindDirection string `json:"windDirection"`
2567 DetailedForecast string `json:"detailedForecast"`
2568 }
2569 
2570 type AlertsResponse struct {
2571 Features []AlertFeature `json:"features"`
2572 }
2573 
2574 type AlertFeature struct {
2575 Properties AlertProperties `json:"properties"`
2576 }
2577 
2578 type AlertProperties struct {
2579 Event string `json:"event"`
2580 AreaDesc string `json:"areaDesc"`
2581 Severity string `json:"severity"`
2582 Description string `json:"description"`
2583 Instruction string `json:"instruction"`
2584 }
2585 
2586 type ForecastInput struct {
2587 Latitude float64 `json:"latitude" jsonschema:"Latitude of the location"`
2588 Longitude float64 `json:"longitude" jsonschema:"Longitude of the location"`
2589 }
2590 
2591 type AlertsInput struct {
2592 State string `json:"state" jsonschema:"Two-letter US state code (e.g. CA, NY)"`
2593 }
2594 ```
2595 
2596 ### Helper functions
2597 
2598 Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
2599 
2600 ```go theme={null}
2601 func makeNWSRequest[T any](ctx context.Context, url string) (*T, error) {
2602 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
2603 if err != nil {
2604 return nil, fmt.Errorf("failed to create request: %w", err)
2605 }
2606 
2607 req.Header.Set("User-Agent", UserAgent)
2608 req.Header.Set("Accept", "application/geo+json")
2609 
2610 client := http.DefaultClient
2611 resp, err := client.Do(req)
2612 if err != nil {
2613 return nil, fmt.Errorf("failed to make request to %s: %w", url, err)
2614 }
2615 defer resp.Body.Close()
2616 
2617 if resp.StatusCode != http.StatusOK {
2618 body, _ := io.ReadAll(resp.Body)
2619 return nil, fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body))
2620 }
2621 
2622 var result T
2623 if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
2624 return nil, fmt.Errorf("failed to decode response: %w", err)
2625 }
2626 
2627 return &result, nil
2628 }
2629 
2630 func formatAlert(alert AlertFeature) string {
2631 props := alert.Properties
2632 event := cmp.Or(props.Event, "Unknown")
2633 areaDesc := cmp.Or(props.AreaDesc, "Unknown")
2634 severity := cmp.Or(props.Severity, "Unknown")
2635 description := cmp.Or(props.Description, "No description available")
2636 instruction := cmp.Or(props.Instruction, "No specific instructions provided")
2637 
2638 return fmt.Sprintf(`
2639 Event: %s
2640 Area: %s
2641 Severity: %s
2642 Description: %s
2643 Instructions: %s
2644 `, event, areaDesc, severity, description, instruction)
2645 }
2646 
2647 func formatPeriod(period ForecastPeriod) string {
2648 return fmt.Sprintf(`
2649 %s:
2650 Temperature: %d°%s
2651 Wind: %s %s
2652 Forecast: %s
2653 `, period.Name, period.Temperature, period.TemperatureUnit,
2654 period.WindSpeed, period.WindDirection, period.DetailedForecast)
2655 }
2656 ```
2657 
2658 ### Implementing tool execution
2659 
2660 The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
2661 
2662 ```go theme={null}
2663 func getForecast(ctx context.Context, req *mcp.CallToolRequest, input ForecastInput) (
2664 *mcp.CallToolResult, any, error,
2665 ) {
2666 // Get points data
2667 pointsURL := fmt.Sprintf("%s/points/%f,%f", NWSAPIBase, input.Latitude, input.Longitude)
2668 pointsData, err := makeNWSRequest[PointsResponse](ctx, pointsURL)
2669 if err != nil {
2670 return &mcp.CallToolResult{
2671 Content: []mcp.Content{
2672 &mcp.TextContent{Text: "Unable to fetch forecast data for this location."},
2673 },
2674 }, nil, nil
2675 }
2676 
2677 // Get forecast data
2678 forecastURL := pointsData.Properties.Forecast
2679 if forecastURL == "" {
2680 return &mcp.CallToolResult{
2681 Content: []mcp.Content{
2682 &mcp.TextContent{Text: "Unable to fetch forecast URL."},
2683 },
2684 }, nil, nil
2685 }
2686 
2687 forecastData, err := makeNWSRequest[ForecastResponse](ctx, forecastURL)
2688 if err != nil {
2689 return &mcp.CallToolResult{
2690 Content: []mcp.Content{
2691 &mcp.TextContent{Text: "Unable to fetch detailed forecast."},
2692 },
2693 }, nil, nil
2694 }
2695 
2696 // Format the periods
2697 periods := forecastData.Properties.Periods
2698 if len(periods) == 0 {
2699 return &mcp.CallToolResult{
2700 Content: []mcp.Content{
2701 &mcp.TextContent{Text: "No forecast periods available."},
2702 },
2703 }, nil, nil
2704 }
2705 
2706 // Show next 5 periods
2707 var forecasts []string
2708 for i := range min(5, len(periods)) {
2709 forecasts = append(forecasts, formatPeriod(periods[i]))
2710 }
2711 
2712 result := strings.Join(forecasts, "\n---\n")
2713 
2714 return &mcp.CallToolResult{
2715 Content: []mcp.Content{
2716 &mcp.TextContent{Text: result},
2717 },
2718 }, nil, nil
2719 }
2720 
2721 func getAlerts(ctx context.Context, req *mcp.CallToolRequest, input AlertsInput) (
2722 *mcp.CallToolResult, any, error,
2723 ) {
2724 // Build alerts URL
2725 stateCode := strings.ToUpper(input.State)
2726 alertsURL := fmt.Sprintf("%s/alerts/active/area/%s", NWSAPIBase, stateCode)
2727 
2728 alertsData, err := makeNWSRequest[AlertsResponse](ctx, alertsURL)
2729 if err != nil {
2730 return &mcp.CallToolResult{
2731 Content: []mcp.Content{
2732 &mcp.TextContent{Text: "Unable to fetch alerts or no alerts found."},
2733 },
2734 }, nil, nil
2735 }
2736 
2737 // Check if there are any alerts
2738 if len(alertsData.Features) == 0 {
2739 return &mcp.CallToolResult{
2740 Content: []mcp.Content{
2741 &mcp.TextContent{Text: "No active alerts for this state."},
2742 },
2743 }, nil, nil
2744 }
2745 
2746 // Format alerts
2747 var alerts []string
2748 for _, feature := range alertsData.Features {
2749 alerts = append(alerts, formatAlert(feature))
2750 }
2751 
2752 result := strings.Join(alerts, "\n---\n")
2753 
2754 return &mcp.CallToolResult{
2755 Content: []mcp.Content{
2756 &mcp.TextContent{Text: result},
2757 },
2758 }, nil, nil
2759 }
2760 ```
2761 
2762 ### Running the server
2763 
2764 Finally, implement the main function to run the server:
2765 
2766 ```go theme={null}
2767 func main() {
2768 // Create MCP server
2769 server := mcp.NewServer(&mcp.Implementation{
2770 Name: "weather",
2771 Version: "1.0.0",
2772 }, nil)
2773 
2774 // Add get_forecast tool
2775 mcp.AddTool(server, &mcp.Tool{
2776 Name: "get_forecast",
2777 Description: "Get weather forecast for a location",
2778 }, getForecast)
2779 
2780 // Add get_alerts tool
2781 mcp.AddTool(server, &mcp.Tool{
2782 Name: "get_alerts",
2783 Description: "Get weather alerts for a US state",
2784 }, getAlerts)
2785 
2786 // Run server on stdio transport
2787 if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil {
2788 log.Fatal(err)
2789 }
2790 }
2791 ```
2792 
2793 Build your server with:
2794 
2795 ```bash theme={null}
2796 go build -o weather .
2797 ```
2798 
2799 The compiled binary will be in `./weather`.
2800 
2801 Let's now test your server from an existing MCP host, Claude for Desktop.
2802 
2803 ## Testing your server with Claude for Desktop
2804 
2805 <Note>
2806 Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/docs/2025-11-25/develop/build-client) tutorial to build an MCP client that connects to the server we just built.
2807 </Note>
2808 
2809 First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
2810 
2811 We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
2812 
2813 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
2814 
2815 <CodeGroup>
2816 ```bash macOS/Linux theme={null}
2817 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
2818 ```
2819 
2820 ```powershell Windows theme={null}
2821 code $env:AppData\Claude\claude_desktop_config.json
2822 ```
2823 </CodeGroup>
2824 
2825 You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
2826 
2827 In this case, we'll add our single weather server like so:
2828 
2829 <CodeGroup>
2830 ```json macOS/Linux theme={null}
2831 {
2832 "mcpServers": {
2833 "weather": {
2834 "command": "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/weather"
2835 }
2836 }
2837 }
2838 ```
2839 
2840 ```json Windows theme={null}
2841 {
2842 "mcpServers": {
2843 "weather": {
2844 "command": "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\weather.exe"
2845 }
2846 }
2847 }
2848 ```
2849 </CodeGroup>
2850 
2851 <Note>
2852 Make sure you pass in the absolute path to your compiled binary. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt from your project directory. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path, and add the `.exe` extension.
2853 </Note>
2854 
2855 This tells Claude for Desktop:
2856 
2857 1. There's an MCP server named "weather"
2858 2. Launch it by running the compiled binary at the specified path
2859 
2860 Save the file, and restart **Claude for Desktop**.
2861 </Tab>
2862</Tabs>
2296 }
2297}
2298```
2299 
2300### Running the server
2301 
2302Finally, implement the main function to run the server with stdio transport:
2303 
2304```rust theme={null}
2305#[tokio::main]
2306async fn main() -> Result<()> {
2307 let transport = (tokio::io::stdin(), tokio::io::stdout());
2308 let service = Weather::new().serve(transport).await?;
2309 service.waiting().await?;
2310 Ok(())
2311}
2312```
2313 
2314Build your server with:
2315 
2316```bash theme={null}
2317cargo build --release
2318```
2319 
2320The compiled binary will be in `target/release/weather`.
2321 
2322Let's now test your server from an existing MCP host, Claude for Desktop.
2323 
2324## Testing your server with Claude for Desktop
2325 
2326> [!NOTE]
2327>
2328> Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/docs/2025-11-25/develop/build-client) tutorial to build an MCP client that connects to the server we just built.
2329 
2330First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
2331 
2332We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
2333 
2334For example, if you have [VS Code](https://code.visualstudio.com/) installed:
2335 
2336```bash macOS/Linux theme={null}
2337code ~/Library/Application\ Support/Claude/claude_desktop_config.json
2338```
2339 
2340```powershell Windows theme={null}
2341code $env:AppData\Claude\claude_desktop_config.json
2342```
2343 
2344You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
2345 
2346In this case, we'll add our single weather server like so:
2347 
2348```json macOS/Linux theme={null}
2349{
2350 "mcpServers": {
2351 "weather": {
2352 "command": "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/target/release/weather"
2353 }
2354 }
2355}
2356```
2357 
2358```json Windows theme={null}
2359{
2360 "mcpServers": {
2361 "weather": {
2362 "command": "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\target\\release\\weather.exe"
2363 }
2364 }
2365}
2366```
2367 
2368> [!NOTE]
2369>
2370> Make sure you pass in the absolute path to your compiled binary. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt from your project directory. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path, and add the `.exe` extension.
2371 
2372This tells Claude for Desktop:
2373 
23741. There's an MCP server named "weather"
23752. Launch it by running the compiled binary at the specified path
2376 
2377Save the file, and restart **Claude for Desktop**.
2378 
2379**Go**
2380 
2381Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-go)
2382 
2383### Prerequisite knowledge
2384 
2385This quickstart assumes you have familiarity with:
2386 
2387* Go
2388* LLMs like Claude
2389 
2390### Logging in MCP Servers
2391 
2392When implementing MCP servers, be careful about how you handle logging:
2393 
2394**For STDIO-based servers:** Never use `fmt.Println()` or `fmt.Printf()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
2395 
2396**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
2397 
2398### Best Practices
2399 
2400* Use `log.Println()` (which defaults to stderr) or a logging library that writes to stderr or files.
2401* Use `fmt.Fprintf(os.Stderr, ...)` to write to stderr explicitly.
2402 
2403### Quick Examples
2404 
2405```go theme={null}
2406// ❌ Bad (STDIO)
2407fmt.Println("Processing request")
2408 
2409// ✅ Good (STDIO)
2410log.Println("Processing request") // defaults to stderr
2411 
2412// ✅ Good (STDIO)
2413fmt.Fprintln(os.Stderr, "Processing request")
2414```
2415 
2416### System requirements
2417 
2418* Go 1.24 or higher installed.
2419 
2420### Set up your environment
2421 
2422First, let's install Go if you haven't already. You can download and install Go from [go.dev](https://go.dev/dl/).
2423 
2424Verify your Go installation:
2425 
2426```bash theme={null}
2427go version
2428```
2429 
2430Now, let's create and set up our project:
2431 
2432```bash macOS/Linux theme={null}
2433# Create a new directory for our project
2434mkdir weather
2435cd weather
2436 
2437# Initialize Go module
2438go mod init weather
2439 
2440# Install dependencies
2441go get github.com/modelcontextprotocol/go-sdk/mcp
2442 
2443# Create our server file
2444touch main.go
2445```
2446 
2447```powershell Windows theme={null}
2448# Create a new directory for our project
2449md weather
2450cd weather
2451 
2452# Initialize Go module
2453go mod init weather
2454 
2455# Install dependencies
2456go get github.com/modelcontextprotocol/go-sdk/mcp
2457 
2458# Create our server file
2459new-item main.go
2460```
2461 
2462Now let's dive into building your server.
2463 
2464## Building your server
2465 
2466### Importing packages and constants
2467 
2468Add these to the top of your `main.go`:
2469 
2470```go theme={null}
2471package main
2472 
2473import (
2474 "cmp"
2475 "context"
2476 "encoding/json"
2477 "fmt"
2478 "io"
2479 "log"
2480 "net/http"
2481 "strings"
2482 
2483 "github.com/modelcontextprotocol/go-sdk/mcp"
2484)
2485 
2486const (
2487 NWSAPIBase = "https://api.weather.gov"
2488 UserAgent = "weather-app/1.0"
2489)
2490```
2491 
2492### Data structures
2493 
2494Next, let's define the data structures used by our tools:
2495 
2496```go theme={null}
2497type PointsResponse struct {
2498 Properties struct {
2499 Forecast string `json:"forecast"`
2500 } `json:"properties"`
2501}
2502 
2503type ForecastResponse struct {
2504 Properties struct {
2505 Periods []ForecastPeriod `json:"periods"`
2506 } `json:"properties"`
2507}
2508 
2509type ForecastPeriod struct {
2510 Name string `json:"name"`
2511 Temperature int `json:"temperature"`
2512 TemperatureUnit string `json:"temperatureUnit"`
2513 WindSpeed string `json:"windSpeed"`
2514 WindDirection string `json:"windDirection"`
2515 DetailedForecast string `json:"detailedForecast"`
2516}
2517 
2518type AlertsResponse struct {
2519 Features []AlertFeature `json:"features"`
2520}
2521 
2522type AlertFeature struct {
2523 Properties AlertProperties `json:"properties"`
2524}
2525 
2526type AlertProperties struct {
2527 Event string `json:"event"`
2528 AreaDesc string `json:"areaDesc"`
2529 Severity string `json:"severity"`
2530 Description string `json:"description"`
2531 Instruction string `json:"instruction"`
2532}
2533 
2534type ForecastInput struct {
2535 Latitude float64 `json:"latitude" jsonschema:"Latitude of the location"`
2536 Longitude float64 `json:"longitude" jsonschema:"Longitude of the location"`
2537}
2538 
2539type AlertsInput struct {
2540 State string `json:"state" jsonschema:"Two-letter US state code (e.g. CA, NY)"`
2541}
2542```
2543 
2544### Helper functions
2545 
2546Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
2547 
2548```go theme={null}
2549func makeNWSRequest[T any](ctx context.Context, url string) (*T, error) {
2550 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
2551 if err != nil {
2552 return nil, fmt.Errorf("failed to create request: %w", err)
2553 }
2554 
2555 req.Header.Set("User-Agent", UserAgent)
2556 req.Header.Set("Accept", "application/geo+json")
2557 
2558 client := http.DefaultClient
2559 resp, err := client.Do(req)
2560 if err != nil {
2561 return nil, fmt.Errorf("failed to make request to %s: %w", url, err)
2562 }
2563 defer resp.Body.Close()
2564 
2565 if resp.StatusCode != http.StatusOK {
2566 body, _ := io.ReadAll(resp.Body)
2567 return nil, fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body))
2568 }
2569 
2570 var result T
2571 if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
2572 return nil, fmt.Errorf("failed to decode response: %w", err)
2573 }
2574 
2575 return &result, nil
2576}
2577 
2578func formatAlert(alert AlertFeature) string {
2579 props := alert.Properties
2580 event := cmp.Or(props.Event, "Unknown")
2581 areaDesc := cmp.Or(props.AreaDesc, "Unknown")
2582 severity := cmp.Or(props.Severity, "Unknown")
2583 description := cmp.Or(props.Description, "No description available")
2584 instruction := cmp.Or(props.Instruction, "No specific instructions provided")
2585 
2586 return fmt.Sprintf(`
2587Event: %s
2588Area: %s
2589Severity: %s
2590Description: %s
2591Instructions: %s
2592`, event, areaDesc, severity, description, instruction)
2593}
2594 
2595func formatPeriod(period ForecastPeriod) string {
2596 return fmt.Sprintf(`
2597%s:
2598Temperature: %d°%s
2599Wind: %s %s
2600Forecast: %s
2601`, period.Name, period.Temperature, period.TemperatureUnit,
2602 period.WindSpeed, period.WindDirection, period.DetailedForecast)
2603}
2604```
2605 
2606### Implementing tool execution
2607 
2608The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
2609 
2610```go theme={null}
2611func getForecast(ctx context.Context, req *mcp.CallToolRequest, input ForecastInput) (
2612 *mcp.CallToolResult, any, error,
2613) {
2614 // Get points data
2615 pointsURL := fmt.Sprintf("%s/points/%f,%f", NWSAPIBase, input.Latitude, input.Longitude)
2616 pointsData, err := makeNWSRequest[PointsResponse](ctx, pointsURL)
2617 if err != nil {
2618 return &mcp.CallToolResult{
2619 Content: []mcp.Content{
2620 &mcp.TextContent{Text: "Unable to fetch forecast data for this location."},
2621 },
2622 }, nil, nil
2623 }
2624 
2625 // Get forecast data
2626 forecastURL := pointsData.Properties.Forecast
2627 if forecastURL == "" {
2628 return &mcp.CallToolResult{
2629 Content: []mcp.Content{
2630 &mcp.TextContent{Text: "Unable to fetch forecast URL."},
2631 },
2632 }, nil, nil
2633 }
2634 
2635 forecastData, err := makeNWSRequest[ForecastResponse](ctx, forecastURL)
2636 if err != nil {
2637 return &mcp.CallToolResult{
2638 Content: []mcp.Content{
2639 &mcp.TextContent{Text: "Unable to fetch detailed forecast."},
2640 },
2641 }, nil, nil
2642 }
2643 
2644 // Format the periods
2645 periods := forecastData.Properties.Periods
2646 if len(periods) == 0 {
2647 return &mcp.CallToolResult{
2648 Content: []mcp.Content{
2649 &mcp.TextContent{Text: "No forecast periods available."},
2650 },
2651 }, nil, nil
2652 }
2653 
2654 // Show next 5 periods
2655 var forecasts []string
2656 for i := range min(5, len(periods)) {
2657 forecasts = append(forecasts, formatPeriod(periods[i]))
2658 }
2659 
2660 result := strings.Join(forecasts, "\n---\n")
2661 
2662 return &mcp.CallToolResult{
2663 Content: []mcp.Content{
2664 &mcp.TextContent{Text: result},
2665 },
2666 }, nil, nil
2667}
2668 
2669func getAlerts(ctx context.Context, req *mcp.CallToolRequest, input AlertsInput) (
2670 *mcp.CallToolResult, any, error,
2671) {
2672 // Build alerts URL
2673 stateCode := strings.ToUpper(input.State)
2674 alertsURL := fmt.Sprintf("%s/alerts/active/area/%s", NWSAPIBase, stateCode)
2675 
2676 alertsData, err := makeNWSRequest[AlertsResponse](ctx, alertsURL)
2677 if err != nil {
2678 return &mcp.CallToolResult{
2679 Content: []mcp.Content{
2680 &mcp.TextContent{Text: "Unable to fetch alerts or no alerts found."},
2681 },
2682 }, nil, nil
2683 }
2684 
2685 // Check if there are any alerts
2686 if len(alertsData.Features) == 0 {
2687 return &mcp.CallToolResult{
2688 Content: []mcp.Content{
2689 &mcp.TextContent{Text: "No active alerts for this state."},
2690 },
2691 }, nil, nil
2692 }
2693 
2694 // Format alerts
2695 var alerts []string
2696 for _, feature := range alertsData.Features {
2697 alerts = append(alerts, formatAlert(feature))
2698 }
2699 
2700 result := strings.Join(alerts, "\n---\n")
2701 
2702 return &mcp.CallToolResult{
2703 Content: []mcp.Content{
2704 &mcp.TextContent{Text: result},
2705 },
2706 }, nil, nil
2707}
2708```
2709 
2710### Running the server
2711 
2712Finally, implement the main function to run the server:
2713 
2714```go theme={null}
2715func main() {
2716 // Create MCP server
2717 server := mcp.NewServer(&mcp.Implementation{
2718 Name: "weather",
2719 Version: "1.0.0",
2720 }, nil)
2721 
2722 // Add get_forecast tool
2723 mcp.AddTool(server, &mcp.Tool{
2724 Name: "get_forecast",
2725 Description: "Get weather forecast for a location",
2726 }, getForecast)
2727 
2728 // Add get_alerts tool
2729 mcp.AddTool(server, &mcp.Tool{
2730 Name: "get_alerts",
2731 Description: "Get weather alerts for a US state",
2732 }, getAlerts)
2733 
2734 // Run server on stdio transport
2735 if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil {
2736 log.Fatal(err)
2737 }
2738}
2739```
2740 
2741Build your server with:
2742 
2743```bash theme={null}
2744go build -o weather .
2745```
2746 
2747The compiled binary will be in `./weather`.
2748 
2749Let's now test your server from an existing MCP host, Claude for Desktop.
2750 
2751## Testing your server with Claude for Desktop
2752 
2753> [!NOTE]
2754>
2755> Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/docs/2025-11-25/develop/build-client) tutorial to build an MCP client that connects to the server we just built.
2756 
2757First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
2758 
2759We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
2760 
2761For example, if you have [VS Code](https://code.visualstudio.com/) installed:
2762 
2763```bash macOS/Linux theme={null}
2764code ~/Library/Application\ Support/Claude/claude_desktop_config.json
2765```
2766 
2767```powershell Windows theme={null}
2768code $env:AppData\Claude\claude_desktop_config.json
2769```
2770 
2771You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
2772 
2773In this case, we'll add our single weather server like so:
2774 
2775```json macOS/Linux theme={null}
2776{
2777 "mcpServers": {
2778 "weather": {
2779 "command": "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/weather"
2780 }
2781 }
2782}
2783```
2784 
2785```json Windows theme={null}
2786{
2787 "mcpServers": {
2788 "weather": {
2789 "command": "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\weather.exe"
2790 }
2791 }
2792}
2793```
2794 
2795> [!NOTE]
2796>
2797> Make sure you pass in the absolute path to your compiled binary. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt from your project directory. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path, and add the `.exe` extension.
2798 
2799This tells Claude for Desktop:
2800 
28011. There's an MCP server named "weather"
28022. Launch it by running the compiled binary at the specified path
2803 
2804Save the file, and restart **Claude for Desktop**.
28632805 
28642806### Test with commands
28652807 
2866Let's make sure Claude for Desktop is picking up the two tools we've exposed in our `weather` server. You can do this by looking for the "Add files, connectors, and more /" <img src="https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/claude-add-files-connectors-and-more.png?fit=max&auto=format&n=cpXzQjUOzyH0mCNH&q=85&s=53acf21f6807dd5323b70b84b5d98d8a" style={{display: 'inline', margin: 0, height: '1.3em'}} width="33" height="33" data-path="images/claude-add-files-connectors-and-more.png" /> icon:
2867 
2868<Frame>
2869 <img src="https://mintcdn.com/mcp/zNouQwo2h8cbxlDS/images/visual-indicator-mcp-tools.png?fit=max&auto=format&n=zNouQwo2h8cbxlDS&q=85&s=1bf23a2cfc5f6dd3dac1c7574cceebc9" width="684" height="133" data-path="images/visual-indicator-mcp-tools.png" />
2870</Frame>
2808Let's make sure Claude for Desktop is picking up the two tools we've exposed in our `weather` server. You can do this by looking for the "Add files, connectors, and more /" ![](https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/claude-add-files-connectors-and-more.png?fit=max\&auto=format\&n=cpXzQjUOzyH0mCNH\&q=85\&s=53acf21f6807dd5323b70b84b5d98d8a) icon:
2809 
2810![](https://mintcdn.com/mcp/zNouQwo2h8cbxlDS/images/visual-indicator-mcp-tools.png?fit=max\&auto=format\&n=zNouQwo2h8cbxlDS\&q=85\&s=1bf23a2cfc5f6dd3dac1c7574cceebc9)
28712811 
28722812After clicking on the plus icon, hover over the "Connectors" menu. You should see the `weather` servers listed:
28732813 
2874<Frame>
2875 <img src="https://mintcdn.com/mcp/zNouQwo2h8cbxlDS/images/available-mcp-tools.png?fit=max&auto=format&n=zNouQwo2h8cbxlDS&q=85&s=e2ace1ac88895a5fe30ebd8d01456bc3" width="437" height="244" data-path="images/available-mcp-tools.png" />
2876</Frame>
2814![](https://mintcdn.com/mcp/zNouQwo2h8cbxlDS/images/available-mcp-tools.png?fit=max\&auto=format\&n=zNouQwo2h8cbxlDS\&q=85\&s=e2ace1ac88895a5fe30ebd8d01456bc3)
28772815 
28782816If your server isn't being picked up by Claude for Desktop, proceed to the [Troubleshooting](#troubleshooting) section for debugging tips.
28792817 
from line 2820
28822820* What's the weather in Sacramento?
28832821* What are the active weather alerts in Texas?
28842822 
2885<Frame>
2886 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/current-weather.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=dce7b2f8a06c20ba358e4bd2e75fa4c7" width="2780" height="1849" data-path="images/current-weather.png" />
2887</Frame>
2888 
2889<Frame>
2890 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/weather-alerts.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=c4762bf2bd84a8781846d2965af3e4a4" width="2809" height="1850" data-path="images/weather-alerts.png" />
2891</Frame>
2892 
2893<Note>
2894 Since this is the US National Weather service, the queries will only work for US locations.
2895</Note>
2823![](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/current-weather.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=dce7b2f8a06c20ba358e4bd2e75fa4c7)
2824 
2825![](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/weather-alerts.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=c4762bf2bd84a8781846d2965af3e4a4)
2826 
2827> [!NOTE]
2828>
2829> Since this is the US National Weather service, the queries will only work for US locations.
28962830 
28972831## What's happening under the hood
28982832 
from line 2841
29072841 
29082842## Troubleshooting
29092843 
2910<AccordionGroup>
2911 <Accordion title="Claude for Desktop Integration Issues">
2912 **Getting logs from Claude for Desktop**
2913 
2914 Claude.app logging related to MCP is written to log files in `~/Library/Logs/Claude`:
2915 
2916 * `mcp.log` will contain general logging about MCP connections and connection failures.
2917 * Files named `mcp-server-SERVERNAME.log` will contain error (stderr) logging from the named server.
2918 
2919 You can run the following command to list recent logs and follow along with any new ones:
2920 
2921 ```bash theme={null}
2922 # Check Claude's logs for errors
2923 tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
2924 ```
2925 
2926 **Server not showing up in Claude**
2927 
2928 1. Check your `claude_desktop_config.json` file syntax
2929 2. Make sure the path to your project is absolute and not relative
2930 3. Restart Claude for Desktop completely
2931 
2932 <Warning>
2933 To properly restart Claude for Desktop, you must fully quit the application:
2934 
2935 * **Windows**: Right-click the Claude icon in the system tray (which may be hidden in the "hidden icons" menu) and select "Quit" or "Exit".
2936 * **macOS**: Use Cmd+Q or select "Quit Claude" from the menu bar.
2937 
2938 Simply closing the window does not fully quit the application, and your MCP server configuration changes will not take effect.
2939 </Warning>
2940 
2941 **Tool calls failing silently**
2942 
2943 If Claude attempts to use the tools but they fail:
2944 
2945 1. Check Claude's logs for errors
2946 2. Verify your server builds and runs without errors
2947 3. Try restarting Claude for Desktop
2948 
2949 **None of this is working. What do I do?**
2950 
2951 Please refer to our [debugging guide](/docs/2025-11-25/tools/debugging) for better debugging tools and more detailed guidance.
2952 </Accordion>
2953 
2954 <Accordion title="Weather API Issues">
2955 **Error: Failed to retrieve grid point data**
2956 
2957 This usually means either:
2958 
2959 1. The coordinates are outside the US
2960 2. The NWS API is having issues
2961 3. You're being rate limited
2962 
2963 Fix:
2964 
2965 * Verify you're using US coordinates
2966 * Add a small delay between requests
2967 * Check the NWS API status page
2968 
2969 **Error: No active alerts for \[STATE]**
2970 
2971 This isn't an error - it just means there are no current weather alerts for that state. Try a different state or check during severe weather.
2972 </Accordion>
2973</AccordionGroup>
2974 
2975<Note>
2976 For more advanced troubleshooting, check out our guide on [Debugging MCP](/docs/2025-11-25/tools/debugging)
2977</Note>
2844> **Claude for Desktop Integration Issues**
2845>
2846> **Getting logs from Claude for Desktop**
2847>
2848> Claude.app logging related to MCP is written to log files in `~/Library/Logs/Claude`:
2849>
2850> * `mcp.log` will contain general logging about MCP connections and connection failures.
2851> * Files named `mcp-server-SERVERNAME.log` will contain error (stderr) logging from the named server.
2852>
2853> You can run the following command to list recent logs and follow along with any new ones:
2854>
2855> ```bash theme={null}
2856> # Check Claude's logs for errors
2857> tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
2858> ```
2859>
2860> **Server not showing up in Claude**
2861>
2862> 1. Check your `claude_desktop_config.json` file syntax
2863>
2864> 2. Make sure the path to your project is absolute and not relative
2865>
2866> 3. Restart Claude for Desktop completely
2867>
2868> > [!WARNING]
2869> >
2870> > To properly restart Claude for Desktop, you must fully quit the application:
2871> >
2872> > * **Windows**: Right-click the Claude icon in the system tray (which may be hidden in the "hidden icons" menu) and select "Quit" or "Exit".
2873> > * **macOS**: Use Cmd+Q or select "Quit Claude" from the menu bar.
2874> >
2875> > Simply closing the window does not fully quit the application, and your MCP server configuration changes will not take effect.
2876>
2877> **Tool calls failing silently**
2878>
2879> If Claude attempts to use the tools but they fail:
2880>
2881> 1. Check Claude's logs for errors
2882> 2. Verify your server builds and runs without errors
2883> 3. Try restarting Claude for Desktop
2884>
2885> **None of this is working. What do I do?**
2886>
2887> Please refer to our [debugging guide](/docs/2025-11-25/tools/debugging) for better debugging tools and more detailed guidance.
2888 
2889> **Weather API Issues**
2890>
2891> **Error: Failed to retrieve grid point data**
2892>
2893> This usually means either:
2894>
2895> 1. The coordinates are outside the US
2896> 2. The NWS API is having issues
2897> 3. You're being rate limited
2898>
2899> Fix:
2900>
2901> * Verify you're using US coordinates
2902> * Add a small delay between requests
2903> * Check the NWS API status page
2904>
2905> **Error: No active alerts for \[STATE]**
2906>
2907> This isn't an error - it just means there are no current weather alerts for that state. Try a different state or check during severe weather.
2908 
2909> [!NOTE]
2910>
2911> For more advanced troubleshooting, check out our guide on [Debugging MCP](/docs/2025-11-25/tools/debugging)
29782912 
29792913## Next steps
29802914 
2981<CardGroup cols={2}>
2982 <Card title="Building a client" icon="outlet" href="/docs/2025-11-25/develop/build-client">
2983 Learn how to build your own MCP client that can connect to your server
2984 </Card>
2985 
2986 <Card title="Example servers" icon="grid" href="/examples">
2987 Check out our gallery of official MCP servers and implementations
2988 </Card>
2989 
2990 <Card title="Debugging Guide" icon="bug" href="/docs/2025-11-25/tools/debugging">
2991 Learn how to effectively debug MCP servers and integrations
2992 </Card>
2993 
2994 <Card title="Build with Agent Skills" icon="comments" href="/docs/2025-11-25/develop/build-with-agent-skills">
2995 Use agent skills to guide AI coding assistants through server design
2996 </Card>
2997</CardGroup>
2915> **[Building a client](/docs/2025-11-25/develop/build-client)**
2916>
2917> Learn how to build your own MCP client that can connect to your server
2918 
2919> **[Example servers](/examples)**
2920>
2921> Check out our gallery of official MCP servers and implementations
2922 
2923> **[Debugging Guide](/docs/2025-11-25/tools/debugging)**
2924>
2925> Learn how to effectively debug MCP servers and integrations
2926 
2927> **[Build with Agent Skills](/docs/2025-11-25/develop/build-with-agent-skills)**
2928>
2929> Use agent skills to guide AI coding assistants through server design
29982930 

docs/2025-11-25/develop/build-with-agent-skills Changed · +9 / -11 lines

from line 85
8585Once your agent scaffolds the server, iterate on tool descriptions and error
8686handling, then test and ship:
8787 
88<CardGroup cols={2}>
89 <Card title="MCP Inspector" icon="magnifying-glass" href="/docs/2025-11-25/tools/inspector">
90 Test your server's tools, resources, and prompts interactively
91 </Card>
88> **[MCP Inspector](/docs/2025-11-25/tools/inspector)**
89>
90> Test your server's tools, resources, and prompts interactively
9291 
93 <Card title="Connect to a client" icon="plug" href="/docs/2025-11-25/develop/connect-local-servers">
94 Wire your server into an MCP client via local or remote configuration
95 </Card>
92> **[Connect to a client](/docs/2025-11-25/develop/connect-local-servers)**
93>
94> Wire your server into an MCP client via local or remote configuration
9695 
97 <Card title="Publish to the Registry" icon="box" href="/registry/quickstart">
98 Make your server discoverable in the MCP Registry
99 </Card>
100</CardGroup>
96> **[Publish to the Registry](/registry/quickstart)**
97>
98> Make your server discoverable in the MCP Registry
10199 

docs/2025-11-25/develop/connect-local-servers Changed · +188 / -212 lines

from line 6
66 
77This guide demonstrates how to connect to local MCP servers using Claude Desktop as an example, one of the many clients that support MCP. While we focus on Claude Desktop's implementation, the concepts apply broadly to other MCP-compatible clients. By the end of this tutorial, Claude will be able to interact with files on your computer, create new documents, organize folders, and search through your file system—all with your explicit permission for each action.
88 
9<Frame>
10 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-filesystem.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=629d7e754dc358d71a408d6ce970c1b1" alt="Claude Desktop with filesystem integration showing file management capabilities" width="1732" height="2060" data-path="images/quickstart-filesystem.png" />
11</Frame>
9![Claude Desktop with filesystem integration showing file management capabilities](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-filesystem.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=629d7e754dc358d71a408d6ce970c1b1)
1210 
1311## Prerequisites
1412 
from line 43
4543 
4644The process involves configuring Claude Desktop to automatically start the Filesystem Server whenever you launch the application. This configuration is done through a JSON file that tells Claude Desktop which servers to run and how to connect to them.
4745 
48<Steps>
49 <Step title="Open Claude Desktop Settings">
50 Start by accessing the Claude Desktop settings. Click on the Claude menu in your system's menu bar (not the settings within the Claude window itself) and select "Settings..."
46**1. Open Claude Desktop Settings**
5147 
52 On macOS, this appears in the top menu bar:
48Start by accessing the Claude Desktop settings. Click on the Claude menu in your system's menu bar (not the settings within the Claude window itself) and select "Settings..."
5349 
54 <Frame style={{ textAlign: "center" }}>
55 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-menu.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=0c8b57e0e17af3624b6762a3ea944c8e" width="400" alt="Claude Desktop menu showing Settings option" data-path="images/quickstart-menu.png" />
56 </Frame>
50On macOS, this appears in the top menu bar:
5751 
58 This opens the Claude Desktop configuration window, which is separate from your Claude account settings.
59 </Step>
52![Claude Desktop menu showing Settings option](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-menu.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=0c8b57e0e17af3624b6762a3ea944c8e)
6053 
61 <Step title="Access Developer Settings">
62 In the Settings window, navigate to the "Developer" tab in the left sidebar. This section contains options for configuring MCP servers and other developer features.
54This opens the Claude Desktop configuration window, which is separate from your Claude account settings.
6355 
64 Click the "Edit Config" button to open the configuration file:
56**2. Access Developer Settings**
6557 
66 <Frame>
67 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-developer.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=0fb595490a2f9e15c0301e771a57446c" alt="Developer settings showing Edit Config button" width="1688" height="534" data-path="images/quickstart-developer.png" />
68 </Frame>
58In the Settings window, navigate to the "Developer" tab in the left sidebar. This section contains options for configuring MCP servers and other developer features.
6959 
70 This action creates a new configuration file if one doesn't exist, or opens your existing configuration. The file is located at:
60Click the "Edit Config" button to open the configuration file:
7161 
72 * **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
73 * **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
74 </Step>
62![Developer settings showing Edit Config button](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-developer.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=0fb595490a2f9e15c0301e771a57446c)
7563 
76 <Step title="Configure the Filesystem Server">
77 Replace the contents of the configuration file with the following JSON structure. This configuration tells Claude Desktop to start the Filesystem Server with access to specific directories:
64This action creates a new configuration file if one doesn't exist, or opens your existing configuration. The file is located at:
7865 
79 <CodeGroup>
80 ```json macOS theme={null}
81 {
82 "mcpServers": {
83 "filesystem": {
84 "command": "npx",
85 "args": [
86 "-y",
87 "@modelcontextprotocol/server-filesystem",
88 "/Users/username/Desktop",
89 "/Users/username/Downloads"
90 ]
91 }
92 }
93 }
94 ```
66* **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
67* **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
9568 
96 ```json Windows theme={null}
97 {
98 "mcpServers": {
99 "filesystem": {
100 "command": "npx",
101 "args": [
102 "-y",
103 "@modelcontextprotocol/server-filesystem",
104 "C:\\Users\\username\\Desktop",
105 "C:\\Users\\username\\Downloads"
106 ]
107 }
108 }
109 }
110 ```
111 </CodeGroup>
69**3. Configure the Filesystem Server**
11270 
113 Replace `username` with your actual computer username. The paths listed in the `args` array specify which directories the Filesystem Server can access. You can modify these paths or add additional directories as needed.
71Replace the contents of the configuration file with the following JSON structure. This configuration tells Claude Desktop to start the Filesystem Server with access to specific directories:
11472 
115 <Tip>
116 **Understanding the Configuration**
73```json macOS theme={null}
74{
75 "mcpServers": {
76 "filesystem": {
77 "command": "npx",
78 "args": [
79 "-y",
80 "@modelcontextprotocol/server-filesystem",
81 "/Users/username/Desktop",
82 "/Users/username/Downloads"
83 ]
84 }
85 }
86}
87```
11788 
118 * `"filesystem"`: A friendly name for the server that appears in Claude Desktop
119 * `"command": "npx"`: Uses Node.js's npx tool to run the server
120 * `"-y"`: Automatically confirms the installation of the server package
121 * `"@modelcontextprotocol/server-filesystem"`: The package name of the Filesystem Server
122 * The remaining arguments: Directories the server is allowed to access
123 </Tip>
89```json Windows theme={null}
90{
91 "mcpServers": {
92 "filesystem": {
93 "command": "npx",
94 "args": [
95 "-y",
96 "@modelcontextprotocol/server-filesystem",
97 "C:\\Users\\username\\Desktop",
98 "C:\\Users\\username\\Downloads"
99 ]
100 }
101 }
102}
103```
124104 
125 <Warning>
126 **Security Consideration**
105Replace `username` with your actual computer username. The paths listed in the `args` array specify which directories the Filesystem Server can access. You can modify these paths or add additional directories as needed.
127106 
128 Only grant access to directories you're comfortable with Claude reading and modifying. The server runs with your user account permissions, so it can perform any file operations you can perform manually.
129 </Warning>
130 </Step>
107> [!TIP]
108>
109> **Understanding the Configuration**
110>
111> * `"filesystem"`: A friendly name for the server that appears in Claude Desktop
112> * `"command": "npx"`: Uses Node.js's npx tool to run the server
113> * `"-y"`: Automatically confirms the installation of the server package
114> * `"@modelcontextprotocol/server-filesystem"`: The package name of the Filesystem Server
115> * The remaining arguments: Directories the server is allowed to access
131116 
132 <Step title="Restart Claude Desktop">
133 After saving the configuration file, completely quit Claude Desktop and restart it. The application needs to restart to load the new configuration and start the MCP server.
117> [!WARNING]
118>
119> **Security Consideration**
120>
121> Only grant access to directories you're comfortable with Claude reading and modifying. The server runs with your user account permissions, so it can perform any file operations you can perform manually.
134122 
135 Upon successful restart, click the "Add files, connectors and more" indicator <img src="https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/claude-add-files-connectors-and-more.png?fit=max&auto=format&n=cpXzQjUOzyH0mCNH&q=85&s=53acf21f6807dd5323b70b84b5d98d8a" style={{display: 'inline', margin: 0, height: '1.3em'}} width="33" height="33" data-path="images/claude-add-files-connectors-and-more.png" /> in the bottom-left corner of the conversation input box:
123**4. Restart Claude Desktop**
136124 
137 <Frame>
138 <img src="https://mintcdn.com/mcp/akpggzunDlIcY2im/images/quickstart-slider.png?fit=max&auto=format&n=akpggzunDlIcY2im&q=85&s=a1ebd4259cff2a7472171885f2edc035" alt="Claude Desktop interface showing MCP server indicator" width="1414" height="410" data-path="images/quickstart-slider.png" />
139 </Frame>
125After saving the configuration file, completely quit Claude Desktop and restart it. The application needs to restart to load the new configuration and start the MCP server.
140126 
141 Click on this indicator, then scroll over "Connectors" and click "Manage connectors". Select "filesystem" from the connector list to view the the Filesystem Server's available tools:
127Upon successful restart, click the "Add files, connectors and more" indicator ![](https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/claude-add-files-connectors-and-more.png?fit=max\&auto=format\&n=cpXzQjUOzyH0mCNH\&q=85\&s=53acf21f6807dd5323b70b84b5d98d8a) in the bottom-left corner of the conversation input box:
142128 
143 <Frame style={{ textAlign: "center" }}>
144 <img src="https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-tools.png?fit=max&auto=format&n=cpXzQjUOzyH0mCNH&q=85&s=212a63d76daba170d52db0d2f6f582be" width="400" alt="Available filesystem tools in Claude Desktop" data-path="images/quickstart-tools.png" />
145 </Frame>
129![Claude Desktop interface showing MCP server indicator](https://mintcdn.com/mcp/akpggzunDlIcY2im/images/quickstart-slider.png?fit=max\&auto=format\&n=akpggzunDlIcY2im\&q=85\&s=a1ebd4259cff2a7472171885f2edc035)
146130 
147 If the Filesystem Server doesn't connect, refer to the [Troubleshooting](#troubleshooting) section for debugging steps.
148 </Step>
149</Steps>
131Click on this indicator, then scroll over "Connectors" and click "Manage connectors". Select "filesystem" from the connector list to view the the Filesystem Server's available tools:
150132 
133![Available filesystem tools in Claude Desktop](https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-tools.png?fit=max\&auto=format\&n=cpXzQjUOzyH0mCNH\&q=85\&s=212a63d76daba170d52db0d2f6f582be)
134 
135If the Filesystem Server doesn't connect, refer to the [Troubleshooting](#troubleshooting) section for debugging steps.
136 
151137## Using the Filesystem Server
152138 
153139With the Filesystem Server connected, Claude can now interact with your file system. Try these example requests to explore the capabilities:
from line 148
162148 
163149Before executing any file system operation, Claude will request your approval. This ensures you maintain control over all actions:
164150 
165<Frame style={{ textAlign: "center" }}>
166 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-approve.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=98cc6e9dfe885fbd6e9bfae40601e494" width="500" alt="Claude requesting approval to perform a file operation" data-path="images/quickstart-approve.png" />
167</Frame>
151![Claude requesting approval to perform a file operation](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-approve.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=98cc6e9dfe885fbd6e9bfae40601e494)
168152 
169153Review each request carefully before approving. You can always deny a request if you're not comfortable with the proposed action.
170154 
from line 156
172156 
173157If you encounter issues setting up or using the Filesystem Server, these solutions address common problems:
174158 
175<AccordionGroup>
176 <Accordion title="Server not showing up in Claude / hammer icon missing">
177 1. Restart Claude Desktop completely
178 2. Check your `claude_desktop_config.json` file syntax
179 3. Make sure the file paths included in `claude_desktop_config.json` are valid and that they are absolute and not relative
180 4. Look at [logs](#getting-logs-from-claude-for-desktop) to see why the server is not connecting
181 5. In your command line, try manually running the server (replacing `username` as you did in `claude_desktop_config.json`) to see if you get any errors:
159> **Server not showing up in Claude / hammer icon missing**
160>
161> 1. Restart Claude Desktop completely
162> 2. Check your `claude_desktop_config.json` file syntax
163> 3. Make sure the file paths included in `claude_desktop_config.json` are valid and that they are absolute and not relative
164> 4. Look at [logs](#getting-logs-from-claude-for-desktop) to see why the server is not connecting
165> 5. In your command line, try manually running the server (replacing `username` as you did in `claude_desktop_config.json`) to see if you get any errors:
166>
167> ```bash macOS/Linux theme={null}
168> npx -y @modelcontextprotocol/server-filesystem /Users/username/Desktop /Users/username/Downloads
169> ```
170>
171> ```powershell Windows theme={null}
172> npx -y @modelcontextprotocol/server-filesystem C:\Users\username\Desktop C:\Users\username\Downloads
173> ```
182174 
183 <CodeGroup>
184 ```bash macOS/Linux theme={null}
185 npx -y @modelcontextprotocol/server-filesystem /Users/username/Desktop /Users/username/Downloads
186 ```
175> **Getting logs from Claude Desktop**
176>
177> Claude.app logging related to MCP is written to log files in:
178>
179> * macOS: `~/Library/Logs/Claude`
180>
181> * Windows: `%APPDATA%\Claude\logs`
182>
183> * `mcp.log` will contain general logging about MCP connections and connection failures.
184>
185> * Files named `mcp-server-SERVERNAME.log` will contain error (stderr) logging from the named server.
186>
187> You can run the following command to list recent logs and follow along with any new ones (on Windows, it will only show recent logs):
188>
189> ```bash macOS/Linux theme={null}
190> tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
191> ```
192>
193> ```powershell Windows theme={null}
194> type "%APPDATA%\Claude\logs\mcp*.log"
195> ```
187196 
188 ```powershell Windows theme={null}
189 npx -y @modelcontextprotocol/server-filesystem C:\Users\username\Desktop C:\Users\username\Downloads
190 ```
191 </CodeGroup>
192 </Accordion>
197> **Tool calls failing silently**
198>
199> If Claude attempts to use the tools but they fail:
200>
201> 1. Check Claude's logs for errors
202> 2. Verify your server builds and runs without errors
203> 3. Try restarting Claude Desktop
193204 
194 <Accordion title="Getting logs from Claude Desktop">
195 Claude.app logging related to MCP is written to log files in:
205> **None of this is working. What do I do?**
206>
207> Please refer to our [debugging guide](/docs/2025-11-25/tools/debugging) for better debugging tools and more detailed guidance.
196208 
197 * macOS: `~/Library/Logs/Claude`
209> **ENOENT error and `$\{APPDATA\}` in paths on Windows**
210>
211> If your configured server fails to load, and you see within its logs an error referring to `${APPDATA}` within a path, you may need to add the expanded value of `%APPDATA%` to your `env` key in `claude_desktop_config.json`:
212>
213> ```json theme={null}
214> {
215> "brave-search": {
216> "command": "npx",
217> "args": ["-y", "@modelcontextprotocol/server-brave-search"],
218> "env": {
219> "APPDATA": "C:\\Users\\user\\AppData\\Roaming\\",
220> "BRAVE_API_KEY": "..."
221> }
222> }
223> }
224> ```
225>
226> With this change in place, launch Claude Desktop once again.
227>
228> > [!WARNING]
229> >
230> > **npm should be installed globally**
231> >
232> > The `npx` command may continue to fail if you have not installed npm globally. If npm is already installed globally, you will find `%APPDATA%\npm` exists on your system. If not, you can install npm globally by running the following command:
233> >
234> > ```bash theme={null}
235> > npm install -g npm
236> > ```
198237 
199 * Windows: `%APPDATA%\Claude\logs`
200 
201 * `mcp.log` will contain general logging about MCP connections and connection failures.
202 
203 * Files named `mcp-server-SERVERNAME.log` will contain error (stderr) logging from the named server.
204 
205 You can run the following command to list recent logs and follow along with any new ones (on Windows, it will only show recent logs):
206 
207 <CodeGroup>
208 ```bash macOS/Linux theme={null}
209 tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
210 ```
211 
212 ```powershell Windows theme={null}
213 type "%APPDATA%\Claude\logs\mcp*.log"
214 ```
215 </CodeGroup>
216 </Accordion>
217 
218 <Accordion title="Tool calls failing silently">
219 If Claude attempts to use the tools but they fail:
220 
221 1. Check Claude's logs for errors
222 2. Verify your server builds and runs without errors
223 3. Try restarting Claude Desktop
224 </Accordion>
225 
226 <Accordion title="None of this is working. What do I do?">
227 Please refer to our [debugging guide](/docs/2025-11-25/tools/debugging) for better debugging tools and more detailed guidance.
228 </Accordion>
229 
230 <Accordion title="ENOENT error and `${APPDATA}` in paths on Windows">
231 If your configured server fails to load, and you see within its logs an error referring to `${APPDATA}` within a path, you may need to add the expanded value of `%APPDATA%` to your `env` key in `claude_desktop_config.json`:
232 
233 ```json theme={null}
234 {
235 "brave-search": {
236 "command": "npx",
237 "args": ["-y", "@modelcontextprotocol/server-brave-search"],
238 "env": {
239 "APPDATA": "C:\\Users\\user\\AppData\\Roaming\\",
240 "BRAVE_API_KEY": "..."
241 }
242 }
243 }
244 ```
245 
246 With this change in place, launch Claude Desktop once again.
247 
248 <Warning>
249 **npm should be installed globally**
250 
251 The `npx` command may continue to fail if you have not installed npm globally. If npm is already installed globally, you will find `%APPDATA%\npm` exists on your system. If not, you can install npm globally by running the following command:
252 
253 ```bash theme={null}
254 npm install -g npm
255 ```
256 </Warning>
257 </Accordion>
258</AccordionGroup>
259 
260238## Next Steps
261239 
262240Now that you've successfully connected Claude Desktop to a local MCP server, explore these options to expand your setup:
263241 
264<CardGroup cols={2}>
265 <Card title="Explore other servers" icon="grid" href="https://github.com/modelcontextprotocol/servers">
266 Browse our collection of official and community-created MCP servers for
267 additional capabilities
268 </Card>
242> **[Explore other servers](https://github.com/modelcontextprotocol/servers)**
243>
244> Browse our collection of official and community-created MCP servers for
245> additional capabilities
269246 
270 <Card title="Build your own server" icon="code" href="/docs/2025-11-25/develop/build-server">
271 Create custom MCP servers tailored to your specific workflows and
272 integrations
273 </Card>
247> **[Build your own server](/docs/2025-11-25/develop/build-server)**
248>
249> Create custom MCP servers tailored to your specific workflows and
250> integrations
274251 
275 <Card title="Connect to remote servers" icon="cloud" href="/docs/2025-11-25/develop/connect-remote-servers">
276 Learn how to connect Claude to remote MCP servers for cloud-based tools and
277 services
278 </Card>
252> **[Connect to remote servers](/docs/2025-11-25/develop/connect-remote-servers)**
253>
254> Learn how to connect Claude to remote MCP servers for cloud-based tools and
255> services
279256 
280 <Card title="Understand the protocol" icon="book" href="/docs/2025-11-25/learn/architecture">
281 Dive deeper into how MCP works and its architecture
282 </Card>
283</CardGroup>
257> **[Understand the protocol](/docs/2025-11-25/learn/architecture)**
258>
259> Dive deeper into how MCP works and its architecture
284260 

docs/2025-11-25/develop/connect-remote-servers Changed · +41 / -57 lines

from line 25
2525 
2626The process of connecting Claude to a remote MCP server involves adding a Custom Connector through the [Claude interface](https://claude.ai/). This establishes a secure connection between Claude and your chosen remote server.
2727 
28<Steps>
29 <Step title="Navigate to Connector Settings">
30 Open Claude in your browser and navigate to the settings page. You can access this by clicking on your profile icon and selecting "Settings" from the dropdown menu. Once in settings, locate and click on the "Connectors" section in the sidebar.
28**1. Navigate to Connector Settings**
3129 
32 This will display your currently configured connectors and provide options to add new ones.
33 </Step>
30Open Claude in your browser and navigate to the settings page. You can access this by clicking on your profile icon and selecting "Settings" from the dropdown menu. Once in settings, locate and click on the "Connectors" section in the sidebar.
3431 
35 <Step title="Add a Custom Connector">
36 In the Connectors section, scroll to the bottom where you'll find the "Add custom connector" button. Click this button to begin the connection process.
32This will display your currently configured connectors and provide options to add new ones.
3733 
38 <Frame>
39 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-remote/1-add-connector.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=b5ae9b23164875bbaa3aff4c178cdc64" alt="Add custom connector button in Claude settings" width="1038" height="809" data-path="images/quickstart-remote/1-add-connector.png" />
40 </Frame>
34**2. Add a Custom Connector**
4135 
42 A dialog will appear prompting you to enter the remote MCP server URL. This URL should be provided by the server developer or administrator. Enter the complete URL, ensuring it includes the proper protocol (https\://) and any necessary path components.
36In the Connectors section, scroll to the bottom where you'll find the "Add custom connector" button. Click this button to begin the connection process.
4337 
44 <Frame>
45 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-remote/2-connect.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=0934f16d8e016cade8e560c8f89d011b" alt="Dialog for entering remote MCP server URL" width="1616" height="282" data-path="images/quickstart-remote/2-connect.png" />
46 </Frame>
38![Add custom connector button in Claude settings](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-remote/1-add-connector.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=b5ae9b23164875bbaa3aff4c178cdc64)
4739 
48 After entering the URL, click "Add" to proceed with the connection.
49 </Step>
40A dialog will appear prompting you to enter the remote MCP server URL. This URL should be provided by the server developer or administrator. Enter the complete URL, ensuring it includes the proper protocol (https\://) and any necessary path components.
5041 
51 <Step title="Complete Authentication">
52 Most remote MCP servers require authentication to ensure secure access to their resources. The authentication process varies depending on the server implementation but commonly involves OAuth, API keys, or username/password combinations.
42![Dialog for entering remote MCP server URL](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-remote/2-connect.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=0934f16d8e016cade8e560c8f89d011b)
5343 
54 <Frame>
55 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-remote/3-auth.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=89af6e1b85718637231388697cc7b015" alt="Authentication screen for remote MCP server" width="490" height="806" data-path="images/quickstart-remote/3-auth.png" />
56 </Frame>
44After entering the URL, click "Add" to proceed with the connection.
5745 
58 Follow the authentication prompts provided by the server. This may redirect you to a third-party authentication provider or display a form within Claude. Once authentication is complete, Claude will establish a secure connection to the remote server.
59 </Step>
46**3. Complete Authentication**
6047 
61 <Step title="Access Resources and Prompts">
62 After successful connection, the remote server's resources and prompts become available in your Claude conversations. You can access these by clicking the paperclip icon in the message input area, which opens the attachment menu.
48Most remote MCP servers require authentication to ensure secure access to their resources. The authentication process varies depending on the server implementation but commonly involves OAuth, API keys, or username/password combinations.
6349 
64 <Frame>
65 <img src="https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-remote/4-select-resources-menu.png?fit=max&auto=format&n=cpXzQjUOzyH0mCNH&q=85&s=e5fa85174f8acbadbd709bac66f42d5c" alt="Attachment menu showing available resources" width="735" height="378" data-path="images/quickstart-remote/4-select-resources-menu.png" />
66 </Frame>
50![Authentication screen for remote MCP server](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-remote/3-auth.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=89af6e1b85718637231388697cc7b015)
6751 
68 The menu displays all available resources and prompts from your connected servers. Select the items you want to include in your conversation. These resources provide Claude with context and information from your external tools.
52Follow the authentication prompts provided by the server. This may redirect you to a third-party authentication provider or display a form within Claude. Once authentication is complete, Claude will establish a secure connection to the remote server.
6953 
70 <Frame>
71 <img src="https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-remote/5-select-prompts-resources.png?fit=max&auto=format&n=cpXzQjUOzyH0mCNH&q=85&s=68722669d9e18252756885c703e4f221" alt="Selecting specific resources and prompts from the menu" width="648" height="529" data-path="images/quickstart-remote/5-select-prompts-resources.png" />
72 </Frame>
73 </Step>
54**4. Access Resources and Prompts**
7455 
75 <Step title="Configure Tool Permissions">
76 Remote MCP servers often expose multiple tools with varying capabilities. You can control which tools Claude is allowed to use by configuring permissions in the connector settings. This ensures Claude only performs actions you've explicitly authorized.
56After successful connection, the remote server's resources and prompts become available in your Claude conversations. You can access these by clicking the paperclip icon in the message input area, which opens the attachment menu.
7757 
78 <Frame>
79 <img src="https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-remote/6-configure-tools.png?fit=max&auto=format&n=cpXzQjUOzyH0mCNH&q=85&s=5cfd8b2c5d06e7e3699eac24c68d090e" alt="Tool permission configuration interface" width="604" height="745" data-path="images/quickstart-remote/6-configure-tools.png" />
80 </Frame>
58![Attachment menu showing available resources](https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-remote/4-select-resources-menu.png?fit=max\&auto=format\&n=cpXzQjUOzyH0mCNH\&q=85\&s=e5fa85174f8acbadbd709bac66f42d5c)
8159 
82 Navigate back to the Connectors settings and click on your connected server. Here you can enable or disable specific tools, set usage limits, and configure other security parameters according to your needs.
83 </Step>
84</Steps>
60The menu displays all available resources and prompts from your connected servers. Select the items you want to include in your conversation. These resources provide Claude with context and information from your external tools.
8561 
62![Selecting specific resources and prompts from the menu](https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-remote/5-select-prompts-resources.png?fit=max\&auto=format\&n=cpXzQjUOzyH0mCNH\&q=85\&s=68722669d9e18252756885c703e4f221)
63 
64**5. Configure Tool Permissions**
65 
66Remote MCP servers often expose multiple tools with varying capabilities. You can control which tools Claude is allowed to use by configuring permissions in the connector settings. This ensures Claude only performs actions you've explicitly authorized.
67 
68![Tool permission configuration interface](https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-remote/6-configure-tools.png?fit=max\&auto=format\&n=cpXzQjUOzyH0mCNH\&q=85\&s=5cfd8b2c5d06e7e3699eac24c68d090e)
69 
70Navigate back to the Connectors settings and click on your connected server. Here you can enable or disable specific tools, set usage limits, and configure other security parameters according to your needs.
71 
8672## Best Practices for Using Remote MCP Servers
8773 
8874When working with remote MCP servers, consider these recommendations to ensure a secure and efficient experience:
from line 81
9581 
9682Now that you've connected Claude to a remote MCP server, you can explore its capabilities in your conversations. Try using the connected tools to automate tasks, access external data, or integrate with your existing workflows.
9783 
98<CardGroup cols={2}>
99 <Card title="Build your own remote server" icon="cloud" href="/docs/2025-11-25/develop/build-server">
100 Create custom remote MCP servers to integrate with proprietary tools and
101 services
102 </Card>
84> **[Build your own remote server](/docs/2025-11-25/develop/build-server)**
85>
86> Create custom remote MCP servers to integrate with proprietary tools and
87> services
10388 
104 <Card title="Explore available servers" icon="grid" href="https://github.com/modelcontextprotocol/servers">
105 Browse our collection of official and community-created MCP servers
106 </Card>
89> **[Explore available servers](https://github.com/modelcontextprotocol/servers)**
90>
91> Browse our collection of official and community-created MCP servers
10792 
108 <Card title="Connect local servers" icon="computer" href="/docs/2025-11-25/develop/connect-local-servers">
109 Learn how to connect Claude Desktop to local MCP servers for direct system
110 access
111 </Card>
93> **[Connect local servers](/docs/2025-11-25/develop/connect-local-servers)**
94>
95> Learn how to connect Claude Desktop to local MCP servers for direct system
96> access
11297 
113 <Card title="Understand the architecture" icon="book" href="/docs/2025-11-25/learn/architecture">
114 Dive deeper into how MCP works and its architecture
115 </Card>
116</CardGroup>
98> **[Understand the architecture](/docs/2025-11-25/learn/architecture)**
99>
100> Dive deeper into how MCP works and its architecture
117101 
118102Remote MCP servers unlock powerful possibilities for extending Claude's capabilities. As you become familiar with these integrations, you'll discover new ways to streamline your workflows and accomplish complex tasks more efficiently.
119103 

docs/2025-11-25/getting-started/intro Changed · +19 / -27 lines

from line 6
66 
77Think of MCP like a USB-C port for AI applications. Just as USB-C provides a standardized way to connect electronic devices, MCP provides a standardized way to connect AI applications to external systems.
88 
9<Frame>
10 <img src="https://mintcdn.com/mcp/bEUxYpZqie0DsluH/images/mcp-simple-diagram.png?fit=max&auto=format&n=bEUxYpZqie0DsluH&q=85&s=35268aa0ad50b8c385913810e7604550" width="3840" height="1500" data-path="images/mcp-simple-diagram.png" />
11</Frame>
9![](https://mintcdn.com/mcp/bEUxYpZqie0DsluH/images/mcp-simple-diagram.png?fit=max\&auto=format\&n=bEUxYpZqie0DsluH\&q=85\&s=35268aa0ad50b8c385913810e7604550)
1210 
1311## What can MCP enable?
1412 
from line 29
3129 
3230## Start Building
3331 
34<CardGroup cols={2}>
35 <Card title="Build servers" icon="server" href="/docs/2025-11-25/develop/build-server">
36 Create MCP servers to expose your data and tools
37 </Card>
32> **[Build servers](/docs/2025-11-25/develop/build-server)**
33>
34> Create MCP servers to expose your data and tools
3835 
39 <Card title="Build clients" icon="computer" href="/docs/2025-11-25/develop/build-client">
40 Develop applications that connect to MCP servers
41 </Card>
36> **[Build clients](/docs/2025-11-25/develop/build-client)**
37>
38> Develop applications that connect to MCP servers
4239 
43 <Card title="Build MCP Apps" icon="puzzle-piece" href="/extensions/apps/overview">
44 Build interactive apps that run inside AI clients
45 </Card>
46</CardGroup>
40> **[Build MCP Apps](/extensions/apps/overview)**
41>
42> Build interactive apps that run inside AI clients
4743 
4844## Learn more
4945 
50<CardGroup cols={2}>
51 <Card title="Architecture" icon="book" href="/docs/2025-11-25/learn/architecture">
52 Learn the core concepts and architecture of MCP
53 </Card>
46> **[Architecture](/docs/2025-11-25/learn/architecture)**
47>
48> Learn the core concepts and architecture of MCP
5449 
55 <Card title="Security" icon="lock" href="/docs/2025-11-25/tutorials/security/security_best_practices">
56 Understand the security considerations and best practices for MCP
57 </Card>
58</CardGroup>
50> **[Security](/docs/2025-11-25/tutorials/security/security_best_practices)**
51>
52> Understand the security considerations and best practices for MCP
5953 
6054## Community
6155 
62<CardGroup cols={2}>
63 <Card title="Contributing" icon="users" href="/community/contributing">
64 Learn how to get involved and contribute to MCP
65 </Card>
66</CardGroup>
56> **[Contributing](/community/contributing)**
57>
58> Learn how to get involved and contribute to MCP
6759 

docs/2025-11-25/learn/architecture Changed · +304 / -312 lines

#### Understanding the Initialization Exchange #### How This Works in AI Applications #### Understanding the Tool Discovery Request #### Understanding the Tool Discovery Response #### How This Works in AI Applications #### Understanding the Tool Execution Request #### Key Elements of Tool Execution #### Understanding the Tool Execution Response #### How This Works in AI Applications #### Understanding Tool List Change Notifications #### Key Features of MCP Notifications #### Client Response to Notifications #### Why Notifications Matter #### How This Works in AI Applications

The two sides of this change are more than 400 edits apart, too far apart to line up, so this is the differ's own diff of it and the words inside a line are not marked.

from line 15
1515* **MCP Development Tools**: Tools for developing MCP servers and clients, including the [MCP Inspector](https://github.com/modelcontextprotocol/inspector)
1616* [MCP Reference Server Implementations](https://github.com/modelcontextprotocol/servers): Reference implementations of MCP servers.
1717 
18<Note>
19 MCP focuses solely on the protocol for context exchange—it does not dictate
20 how AI applications use LLMs or manage the provided context.
21</Note>
18> [!NOTE]
19>
20> MCP focuses solely on the protocol for context exchange—it does not dictate
21> how AI applications use LLMs or manage the provided context.
2222 
2323## Concepts of MCP
2424 
from line 104
104104 
105105#### Lifecycle management
106106 
107MCP is a <Tooltip tip="A subset of MCP can be made stateless using the Streamable HTTP transport">stateful protocol</Tooltip> that requires lifecycle management. The purpose of lifecycle management is to negotiate the <Tooltip tip="Features and operations that a client or server supports, such as tools, resources, or prompts">capabilities</Tooltip> that both client and server support. Detailed information can be found in the [specification](/specification/2025-11-25/basic/lifecycle), and the [example](#example) showcases the initialization sequence.
107MCP is a stateful protocol (A subset of MCP can be made stateless using the Streamable HTTP transport) that requires lifecycle management. The purpose of lifecycle management is to negotiate the capabilities (Features and operations that a client or server supports, such as tools, resources, or prompts) that both client and server support. Detailed information can be found in the [specification](/specification/2025-11-25/basic/lifecycle), and the [example](#example) showcases the initialization sequence.
108108 
109109#### Primitives
110110 
from line 145
145145 
146146This section provides a step-by-step walkthrough of an MCP client-server interaction, focusing on the data layer protocol. We'll demonstrate the lifecycle sequence, tool operations, and notifications using JSON-RPC 2.0 messages.
147147 
148<Steps>
149 <Step title="Initialization (Lifecycle Management)">
150 MCP begins with lifecycle management through a capability negotiation handshake. As described in the [lifecycle management](#lifecycle-management) section, the client sends an `initialize` request to establish the connection and negotiate supported features.
151 
152 <CodeGroup>
153 ```json Initialize Request theme={null}
148**1. Initialization (Lifecycle Management)**
149 
150MCP begins with lifecycle management through a capability negotiation handshake. As described in the [lifecycle management](#lifecycle-management) section, the client sends an `initialize` request to establish the connection and negotiate supported features.
151 
152```json Initialize Request theme={null}
153{
154 "jsonrpc": "2.0",
155 "id": 1,
156 "method": "initialize",
157 "params": {
158 "protocolVersion": "2025-11-25",
159 "capabilities": {
160 "elicitation": {}
161 },
162 "clientInfo": {
163 "name": "example-client",
164 "version": "1.0.0"
165 }
166 }
167}
168```
169 
170```json Initialize Response theme={null}
171{
172 "jsonrpc": "2.0",
173 "id": 1,
174 "result": {
175 "protocolVersion": "2025-11-25",
176 "capabilities": {
177 "tools": {
178 "listChanged": true
179 },
180 "resources": {}
181 },
182 "serverInfo": {
183 "name": "example-server",
184 "version": "1.0.0"
185 }
186 }
187}
188```
189 
190#### Understanding the Initialization Exchange
191 
192The initialization process is a key part of MCP's lifecycle management and serves several critical purposes:
193 
1941. **Protocol Version Negotiation**: The `protocolVersion` field (e.g., "2025-11-25") ensures both client and server are using compatible protocol versions. This prevents communication errors that could occur when different versions attempt to interact. If a mutually compatible version is not negotiated, the connection should be terminated.
195 
1962. **Capability Discovery**: The `capabilities` object allows each party to declare what features they support, including which [primitives](#primitives) they can handle (tools, resources, prompts) and whether they support features like [notifications](#notifications). This enables efficient communication by avoiding unsupported operations.
197 
1983. **Identity Exchange**: The `clientInfo` and `serverInfo` objects provide identification and versioning information for debugging and compatibility purposes.
199 
200In this example, the capability negotiation demonstrates how MCP primitives are declared:
201 
202**Client Capabilities**:
203 
204* `"elicitation": {}` - The client declares it can work with user interaction requests (can receive `elicitation/create` method calls)
205 
206**Server Capabilities**:
207 
208* `"tools": {"listChanged": true}` - The server supports the tools primitive AND can send `tools/list_changed` notifications when its tool list changes
209* `"resources": {}` - The server also supports the resources primitive (can handle `resources/list` and `resources/read` methods)
210 
211After successful initialization, the client sends a notification to indicate it's ready:
212 
213```json Notification theme={null}
214{
215 "jsonrpc": "2.0",
216 "method": "notifications/initialized"
217}
218```
219 
220#### How This Works in AI Applications
221 
222During initialization, the AI application's MCP client manager establishes connections to configured servers and stores their capabilities for later use. The application uses this information to determine which servers can provide specific types of functionality (tools, resources, prompts) and whether they support real-time updates.
223 
224```python Pseudo-code for AI application initialization theme={null}
225# Pseudo Code
226async with stdio_client(server_config) as (read, write):
227 async with ClientSession(read, write) as session:
228 init_response = await session.initialize()
229 if init_response.capabilities.tools:
230 app.register_mcp_server(session, supports_tools=True)
231 app.set_server_ready(session)
232```
233 
234**2. Tool Discovery (Primitives)**
235 
236Now that the connection is established, the client can discover available tools by sending a `tools/list` request. This request is fundamental to MCP's tool discovery mechanism — it allows clients to understand what tools are available on the server before attempting to use them.
237 
238```json Tools List Request theme={null}
239{
240 "jsonrpc": "2.0",
241 "id": 2,
242 "method": "tools/list"
243}
244```
245 
246```json Tools List Response theme={null}
247{
248 "jsonrpc": "2.0",
249 "id": 2,
250 "result": {
251 "tools": [
154252 {
155 "jsonrpc": "2.0",
156 "id": 1,
157 "method": "initialize",
158 "params": {
159 "protocolVersion": "2025-11-25",
160 "capabilities": {
161 "elicitation": {}
253 "name": "calculator_arithmetic",
254 "title": "Calculator",
255 "description": "Perform mathematical calculations including basic arithmetic, trigonometric functions, and algebraic operations",
256 "inputSchema": {
257 "type": "object",
258 "properties": {
259 "expression": {
260 "type": "string",
261 "description": "Mathematical expression to evaluate (e.g., '2 + 3 * 4', 'sin(30)', 'sqrt(16)')"
262 }
162263 },
163 "clientInfo": {
164 "name": "example-client",
165 "version": "1.0.0"
166 }
264 "required": ["expression"]
265 }
266 },
267 {
268 "name": "weather_current",
269 "title": "Weather Information",
270 "description": "Get current weather information for any location worldwide",
271 "inputSchema": {
272 "type": "object",
273 "properties": {
274 "location": {
275 "type": "string",
276 "description": "City name, address, or coordinates (latitude,longitude)"
277 },
278 "units": {
279 "type": "string",
280 "enum": ["metric", "imperial", "kelvin"],
281 "description": "Temperature units to use in response",
282 "default": "metric"
283 }
284 },
285 "required": ["location"]
167286 }
168287 }
169 ```
170 
171 ```json Initialize Response theme={null}
288 ]
289 }
290}
291```
292 
293#### Understanding the Tool Discovery Request
294 
295The `tools/list` request is simple, containing no parameters.
296 
297#### Understanding the Tool Discovery Response
298 
299The response contains a `tools` array that provides comprehensive metadata about each available tool. This array-based structure allows servers to expose multiple tools simultaneously while maintaining clear boundaries between different functionalities.
300 
301Each tool object in the response includes several key fields:
302 
303* **`name`**: A unique identifier for the tool within the server's namespace. This serves as the primary key for tool execution and should follow a clear naming pattern (e.g., `calculator_arithmetic` rather than just `calculate`)
304* **`title`**: A human-readable display name for the tool that clients can show to users
305* **`description`**: Detailed explanation of what the tool does and when to use it
306* **`inputSchema`**: A JSON Schema that defines the expected input parameters, enabling type validation and providing clear documentation about required and optional parameters
307 
308#### How This Works in AI Applications
309 
310The AI application fetches available tools from all connected MCP servers and combines them into a unified tool registry that the language model can access. This allows the LLM to understand what actions it can perform and automatically generates the appropriate tool calls during conversations.
311 
312```python Pseudo-code for AI application tool discovery theme={null}
313# Pseudo-code using MCP Python SDK patterns
314available_tools = []
315for session in app.mcp_server_sessions():
316 tools_response = await session.list_tools()
317 available_tools.extend(tools_response.tools)
318conversation.register_available_tools(available_tools)
319```
320 
321**3. Tool Execution (Primitives)**
322 
323The client can now execute a tool using the `tools/call` method. This demonstrates how MCP primitives are used in practice: after discovering available tools, the client can invoke them with appropriate arguments.
324 
325#### Understanding the Tool Execution Request
326 
327The `tools/call` request follows a structured format that ensures type safety and clear communication between client and server. Note that we're using the proper tool name from the discovery response (`weather_current`) rather than a simplified name:
328 
329```json Tool Call Request theme={null}
330{
331 "jsonrpc": "2.0",
332 "id": 3,
333 "method": "tools/call",
334 "params": {
335 "name": "weather_current",
336 "arguments": {
337 "location": "San Francisco",
338 "units": "imperial"
339 }
340 }
341}
342```
343 
344```json Tool Call Response theme={null}
345{
346 "jsonrpc": "2.0",
347 "id": 3,
348 "result": {
349 "content": [
172350 {
173 "jsonrpc": "2.0",
174 "id": 1,
175 "result": {
176 "protocolVersion": "2025-11-25",
177 "capabilities": {
178 "tools": {
179 "listChanged": true
180 },
181 "resources": {}
182 },
183 "serverInfo": {
184 "name": "example-server",
185 "version": "1.0.0"
186 }
187 }
351 "type": "text",
352 "text": "Current weather in San Francisco: 68°F, partly cloudy with light winds from the west at 8 mph. Humidity: 65%"
188353 }
189 ```
190 </CodeGroup>
191 
192 #### Understanding the Initialization Exchange
193 
194 The initialization process is a key part of MCP's lifecycle management and serves several critical purposes:
195 
196 1. **Protocol Version Negotiation**: The `protocolVersion` field (e.g., "2025-11-25") ensures both client and server are using compatible protocol versions. This prevents communication errors that could occur when different versions attempt to interact. If a mutually compatible version is not negotiated, the connection should be terminated.
197 
198 2. **Capability Discovery**: The `capabilities` object allows each party to declare what features they support, including which [primitives](#primitives) they can handle (tools, resources, prompts) and whether they support features like [notifications](#notifications). This enables efficient communication by avoiding unsupported operations.
199 
200 3. **Identity Exchange**: The `clientInfo` and `serverInfo` objects provide identification and versioning information for debugging and compatibility purposes.
201 
202 In this example, the capability negotiation demonstrates how MCP primitives are declared:
203 
204 **Client Capabilities**:
205 
206 * `"elicitation": {}` - The client declares it can work with user interaction requests (can receive `elicitation/create` method calls)
207 
208 **Server Capabilities**:
209 
210 * `"tools": {"listChanged": true}` - The server supports the tools primitive AND can send `tools/list_changed` notifications when its tool list changes
211 * `"resources": {}` - The server also supports the resources primitive (can handle `resources/list` and `resources/read` methods)
212 
213 After successful initialization, the client sends a notification to indicate it's ready:
214 
215 ```json Notification theme={null}
216 {
217 "jsonrpc": "2.0",
218 "method": "notifications/initialized"
219 }
220 ```
221 
222 #### How This Works in AI Applications
223 
224 During initialization, the AI application's MCP client manager establishes connections to configured servers and stores their capabilities for later use. The application uses this information to determine which servers can provide specific types of functionality (tools, resources, prompts) and whether they support real-time updates.
225 
226 ```python Pseudo-code for AI application initialization theme={null}
227 # Pseudo Code
228 async with stdio_client(server_config) as (read, write):
229 async with ClientSession(read, write) as session:
230 init_response = await session.initialize()
231 if init_response.capabilities.tools:
232 app.register_mcp_server(session, supports_tools=True)
233 app.set_server_ready(session)
234 ```
235 </Step>
236 
237 <Step title="Tool Discovery (Primitives)">
238 Now that the connection is established, the client can discover available tools by sending a `tools/list` request. This request is fundamental to MCP's tool discovery mechanism — it allows clients to understand what tools are available on the server before attempting to use them.
239 
240 <CodeGroup>
241 ```json Tools List Request theme={null}
242 {
243 "jsonrpc": "2.0",
244 "id": 2,
245 "method": "tools/list"
246 }
247 ```
248 
249 ```json Tools List Response theme={null}
250 {
251 "jsonrpc": "2.0",
252 "id": 2,
253 "result": {
254 "tools": [
255 {
256 "name": "calculator_arithmetic",
257 "title": "Calculator",
258 "description": "Perform mathematical calculations including basic arithmetic, trigonometric functions, and algebraic operations",
259 "inputSchema": {
260 "type": "object",
261 "properties": {
262 "expression": {
263 "type": "string",
264 "description": "Mathematical expression to evaluate (e.g., '2 + 3 * 4', 'sin(30)', 'sqrt(16)')"
265 }
266 },
267 "required": ["expression"]
268 }
269 },
270 {
271 "name": "weather_current",
272 "title": "Weather Information",
273 "description": "Get current weather information for any location worldwide",
274 "inputSchema": {
275 "type": "object",
276 "properties": {
277 "location": {
278 "type": "string",
279 "description": "City name, address, or coordinates (latitude,longitude)"
280 },
281 "units": {
282 "type": "string",
283 "enum": ["metric", "imperial", "kelvin"],
284 "description": "Temperature units to use in response",
285 "default": "metric"
286 }
287 },
288 "required": ["location"]
289 }
290 }
291 ]
292 }
293 }
294 ```
295 </CodeGroup>
296 
297 #### Understanding the Tool Discovery Request
298 
299 The `tools/list` request is simple, containing no parameters.
300 
301 #### Understanding the Tool Discovery Response
302 
303 The response contains a `tools` array that provides comprehensive metadata about each available tool. This array-based structure allows servers to expose multiple tools simultaneously while maintaining clear boundaries between different functionalities.
304 
305 Each tool object in the response includes several key fields:
306 
307 * **`name`**: A unique identifier for the tool within the server's namespace. This serves as the primary key for tool execution and should follow a clear naming pattern (e.g., `calculator_arithmetic` rather than just `calculate`)
308 * **`title`**: A human-readable display name for the tool that clients can show to users
309 * **`description`**: Detailed explanation of what the tool does and when to use it
310 * **`inputSchema`**: A JSON Schema that defines the expected input parameters, enabling type validation and providing clear documentation about required and optional parameters
311 
312 #### How This Works in AI Applications
313 
314 The AI application fetches available tools from all connected MCP servers and combines them into a unified tool registry that the language model can access. This allows the LLM to understand what actions it can perform and automatically generates the appropriate tool calls during conversations.
315 
316 ```python Pseudo-code for AI application tool discovery theme={null}
317 # Pseudo-code using MCP Python SDK patterns
318 available_tools = []
319 for session in app.mcp_server_sessions():
320 tools_response = await session.list_tools()
321 available_tools.extend(tools_response.tools)
322 conversation.register_available_tools(available_tools)
323 ```
324 </Step>
325 
326 <Step title="Tool Execution (Primitives)">
327 The client can now execute a tool using the `tools/call` method. This demonstrates how MCP primitives are used in practice: after discovering available tools, the client can invoke them with appropriate arguments.
328 
329 #### Understanding the Tool Execution Request
330 
331 The `tools/call` request follows a structured format that ensures type safety and clear communication between client and server. Note that we're using the proper tool name from the discovery response (`weather_current`) rather than a simplified name:
332 
333 <CodeGroup>
334 ```json Tool Call Request theme={null}
335 {
336 "jsonrpc": "2.0",
337 "id": 3,
338 "method": "tools/call",
339 "params": {
340 "name": "weather_current",
341 "arguments": {
342 "location": "San Francisco",
343 "units": "imperial"
344 }
345 }
346 }
347 ```
348 
349 ```json Tool Call Response theme={null}
350 {
351 "jsonrpc": "2.0",
352 "id": 3,
353 "result": {
354 "content": [
355 {
356 "type": "text",
357 "text": "Current weather in San Francisco: 68°F, partly cloudy with light winds from the west at 8 mph. Humidity: 65%"
358 }
359 ]
360 }
361 }
362 ```
363 </CodeGroup>
364 
365 #### Key Elements of Tool Execution
366 
367 The request structure includes several important components:
368 
369 1. **`name`**: Must match exactly the tool name from the discovery response (`weather_current`). This ensures the server can correctly identify which tool to execute.
370 
371 2. **`arguments`**: Contains the input parameters as defined by the tool's `inputSchema`. In this example:
372 * `location`: "San Francisco" (required parameter)
373 * `units`: "imperial" (optional parameter, defaults to "metric" if not specified)
374 
375 3. **JSON-RPC Structure**: Uses standard JSON-RPC 2.0 format with unique `id` for request-response correlation.
376 
377 #### Understanding the Tool Execution Response
378 
379 The response demonstrates MCP's flexible content system:
380 
381 1. **`content` Array**: Tool responses return an array of content objects, allowing for rich, multi-format responses (text, images, resources, etc.)
382 
383 2. **Content Types**: Each content object has a `type` field. In this example, `"type": "text"` indicates plain text content, but MCP supports various content types for different use cases.
384 
385 3. **Structured Output**: The response provides actionable information that the AI application can use as context for language model interactions.
386 
387 This execution pattern allows AI applications to dynamically invoke server functionality and receive structured responses that can be integrated into conversations with language models.
388 
389 #### How This Works in AI Applications
390 
391 When the language model decides to use a tool during a conversation, the AI application intercepts the tool call, routes it to the appropriate MCP server, executes it, and returns the results back to the LLM as part of the conversation flow. This enables the LLM to access real-time data and perform actions in the external world.
392 
393 ```python theme={null}
394 # Pseudo-code for AI application tool execution
395 async def handle_tool_call(conversation, tool_name, arguments):
396 session = app.find_mcp_session_for_tool(tool_name)
397 result = await session.call_tool(tool_name, arguments)
398 conversation.add_tool_result(result.content)
399 ```
400 </Step>
401 
402 <Step title="Real-time Updates (Notifications)">
403 MCP supports real-time notifications that enable servers to inform clients about changes without being explicitly requested. This demonstrates the notification system, a key feature that keeps MCP connections synchronized and responsive.
404 
405 #### Understanding Tool List Change Notifications
406 
407 When the server's available tools change—such as when new functionality becomes available, existing tools are modified, or tools become temporarily unavailable—the server can proactively notify connected clients:
408 
409 ```json Request theme={null}
410 {
411 "jsonrpc": "2.0",
412 "method": "notifications/tools/list_changed"
413 }
414 ```
415 
416 #### Key Features of MCP Notifications
417 
418 1. **No Response Required**: Notice there's no `id` field in the notification. This follows JSON-RPC 2.0 notification semantics where no response is expected or sent.
419 
420 2. **Capability-Based**: This notification is only sent by servers that declared `"listChanged": true` in their tools capability during initialization (as shown in Step 1).
421 
422 3. **Event-Driven**: The server decides when to send notifications based on internal state changes, making MCP connections dynamic and responsive.
423 
424 #### Client Response to Notifications
425 
426 Upon receiving this notification, the client typically reacts by requesting the updated tool list. This creates a refresh cycle that keeps the client's understanding of available tools current:
427 
428 ```json Request theme={null}
429 {
430 "jsonrpc": "2.0",
431 "id": 4,
432 "method": "tools/list"
433 }
434 ```
435 
436 #### Why Notifications Matter
437 
438 This notification system is crucial for several reasons:
439 
440 1. **Dynamic Environments**: Tools may come and go based on server state, external dependencies, or user permissions
441 2. **Efficiency**: Clients don't need to poll for changes; they're notified when updates occur
442 3. **Consistency**: Ensures clients always have accurate information about available server capabilities
443 4. **Real-time Collaboration**: Enables responsive AI applications that can adapt to changing contexts
444 
445 This notification pattern extends beyond tools to other MCP primitives, enabling comprehensive real-time synchronization between clients and servers.
446 
447 #### How This Works in AI Applications
448 
449 When the AI application receives a notification about changed tools, it immediately refreshes its tool registry and updates the LLM's available capabilities. This ensures that ongoing conversations always have access to the most current set of tools, and the LLM can dynamically adapt to new functionality as it becomes available.
450 
451 ```python theme={null}
452 # Pseudo-code for AI application notification handling
453 async def handle_tools_changed_notification(session):
454 tools_response = await session.list_tools()
455 app.update_available_tools(session, tools_response.tools)
456 if app.conversation.is_active():
457 app.conversation.notify_llm_of_new_capabilities()
458 ```
459 </Step>
460</Steps>
354 ]
355 }
356}
357```
358 
359#### Key Elements of Tool Execution
360 
361The request structure includes several important components:
362 
3631. **`name`**: Must match exactly the tool name from the discovery response (`weather_current`). This ensures the server can correctly identify which tool to execute.
364 
3652. **`arguments`**: Contains the input parameters as defined by the tool's `inputSchema`. In this example:
366 * `location`: "San Francisco" (required parameter)
367 * `units`: "imperial" (optional parameter, defaults to "metric" if not specified)
368 
3693. **JSON-RPC Structure**: Uses standard JSON-RPC 2.0 format with unique `id` for request-response correlation.
370 
371#### Understanding the Tool Execution Response
372 
373The response demonstrates MCP's flexible content system:
374 
3751. **`content` Array**: Tool responses return an array of content objects, allowing for rich, multi-format responses (text, images, resources, etc.)
376 
3772. **Content Types**: Each content object has a `type` field. In this example, `"type": "text"` indicates plain text content, but MCP supports various content types for different use cases.
378 
3793. **Structured Output**: The response provides actionable information that the AI application can use as context for language model interactions.
380 
381This execution pattern allows AI applications to dynamically invoke server functionality and receive structured responses that can be integrated into conversations with language models.
382 
383#### How This Works in AI Applications
384 
385When the language model decides to use a tool during a conversation, the AI application intercepts the tool call, routes it to the appropriate MCP server, executes it, and returns the results back to the LLM as part of the conversation flow. This enables the LLM to access real-time data and perform actions in the external world.
386 
387```python theme={null}
388# Pseudo-code for AI application tool execution
389async def handle_tool_call(conversation, tool_name, arguments):
390 session = app.find_mcp_session_for_tool(tool_name)
391 result = await session.call_tool(tool_name, arguments)
392 conversation.add_tool_result(result.content)
393```
394 
395**4. Real-time Updates (Notifications)**
396 
397MCP supports real-time notifications that enable servers to inform clients about changes without being explicitly requested. This demonstrates the notification system, a key feature that keeps MCP connections synchronized and responsive.
398 
399#### Understanding Tool List Change Notifications
400 
401When the server's available tools change—such as when new functionality becomes available, existing tools are modified, or tools become temporarily unavailable—the server can proactively notify connected clients:
402 
403```json Request theme={null}
404{
405 "jsonrpc": "2.0",
406 "method": "notifications/tools/list_changed"
407}
408```
409 
410#### Key Features of MCP Notifications
411 
4121. **No Response Required**: Notice there's no `id` field in the notification. This follows JSON-RPC 2.0 notification semantics where no response is expected or sent.
413 
4142. **Capability-Based**: This notification is only sent by servers that declared `"listChanged": true` in their tools capability during initialization (as shown in Step 1).
415 
4163. **Event-Driven**: The server decides when to send notifications based on internal state changes, making MCP connections dynamic and responsive.
417 
418#### Client Response to Notifications
419 
420Upon receiving this notification, the client typically reacts by requesting the updated tool list. This creates a refresh cycle that keeps the client's understanding of available tools current:
421 
422```json Request theme={null}
423{
424 "jsonrpc": "2.0",
425 "id": 4,
426 "method": "tools/list"
427}
428```
429 
430#### Why Notifications Matter
431 
432This notification system is crucial for several reasons:
433 
4341. **Dynamic Environments**: Tools may come and go based on server state, external dependencies, or user permissions
4352. **Efficiency**: Clients don't need to poll for changes; they're notified when updates occur
4363. **Consistency**: Ensures clients always have accurate information about available server capabilities
4374. **Real-time Collaboration**: Enables responsive AI applications that can adapt to changing contexts
438 
439This notification pattern extends beyond tools to other MCP primitives, enabling comprehensive real-time synchronization between clients and servers.
440 
441#### How This Works in AI Applications
442 
443When the AI application receives a notification about changed tools, it immediately refreshes its tool registry and updates the LLM's available capabilities. This ensures that ongoing conversations always have access to the most current set of tools, and the LLM can dynamically adapt to new functionality as it becomes available.
444 
445```python theme={null}
446# Pseudo-code for AI application notification handling
447async def handle_tools_changed_notification(session):
448 tools_response = await session.list_tools()
449 app.update_available_tools(session, tools_response.tools)
450 if app.conversation.is_active():
451 app.conversation.notify_llm_of_new_capabilities()
452```
461453 

docs/2025-11-25/learn/server-concepts Changed · +3 / -3 lines

from line 10
1010 
1111| Feature | Explanation | Examples | Who controls it |
1212| - | - | - | - |
13| **Tools** | Functions that your LLM can actively call, and decides when to use them based on user requests. Tools can write to databases, call external APIs, modify files, or trigger other logic. | Search flights<br />Send messages<br />Create calendar events | Model |
14| **Resources** | Passive data sources that provide read-only access to information for context, such as file contents, database schemas, or API documentation. | Retrieve documents<br />Access knowledge bases<br />Read calendars | Application |
15| **Prompts** | Pre-built instruction templates that tell the model to work with specific tools and resources. | Plan a vacation<br />Summarize my meetings<br />Draft an email | User |
13| **Tools** | Functions that your LLM can actively call, and decides when to use them based on user requests. Tools can write to databases, call external APIs, modify files, or trigger other logic. | Search flights Send messages Create calendar events | Model |
14| **Resources** | Passive data sources that provide read-only access to information for context, such as file contents, database schemas, or API documentation. | Retrieve documents Access knowledge bases Read calendars | Application |
15| **Prompts** | Pre-built instruction templates that tell the model to work with specific tools and resources. | Plan a vacation Summarize my meetings Draft an email | User |
1616 
1717We will use a hypothetical scenario to demonstrate the role of each of these features, and show how they can work together.
1818 

docs/2025-11-25/learn/versioning Changed · +5 / -5 lines

from line 3
33The Model Context Protocol uses string-based version identifiers following the format
44`YYYY-MM-DD`, to indicate the last date backwards incompatible changes were made.
55 
6<Info>
7 The protocol version will *not* be incremented when the
8 protocol is updated, as long as the changes maintain backwards compatibility. This allows
9 for incremental improvements while preserving interoperability.
10</Info>
6> [!NOTE]
7>
8> The protocol version will *not* be incremented when the
9> protocol is updated, as long as the changes maintain backwards compatibility. This allows
10> for incremental improvements while preserving interoperability.
1111 
1212## Revisions
1313 

docs/2025-11-25/sdk Changed · +16 / -18 lines

from line 8
88 
99| SDK | Repository | Tier |
1010| :- | :- | -: |
11| <Icon icon="square-js" size={24} />   [TypeScript](https://ts.sdk.modelcontextprotocol.io) | [modelcontextprotocol/typescript-sdk](https://github.com/modelcontextprotocol/typescript-sdk) | <Badge color="blue" shape="pill">Tier 1</Badge> |
12| <Icon icon="python" size={24} />   [Python](https://py.sdk.modelcontextprotocol.io) | [modelcontextprotocol/python-sdk](https://github.com/modelcontextprotocol/python-sdk) | <Badge color="blue" shape="pill">Tier 1</Badge> |
13| <Icon icon="square-c" size={24} />   [C#](https://csharp.sdk.modelcontextprotocol.io) | [modelcontextprotocol/csharp-sdk](https://github.com/modelcontextprotocol/csharp-sdk) | <Badge color="blue" shape="pill">Tier 1</Badge> |
14| <Icon icon="golang" size={24} />   [Go](https://go.sdk.modelcontextprotocol.io) | [modelcontextprotocol/go-sdk](https://github.com/modelcontextprotocol/go-sdk) | <Badge color="blue" shape="pill">Tier 1</Badge> |
15| <Icon icon="java" size={24} />   [Java](https://java.sdk.modelcontextprotocol.io) | [modelcontextprotocol/java-sdk](https://github.com/modelcontextprotocol/java-sdk) | <Badge color="purple" shape="pill">Tier 2</Badge> |
16| <Icon icon="rust" size={24} />   [Rust](https://rust.sdk.modelcontextprotocol.io) | [modelcontextprotocol/rust-sdk](https://github.com/modelcontextprotocol/rust-sdk) | <Badge color="purple" shape="pill">Tier 2</Badge> |
17| <Icon icon="swift" size={24} />   Swift | [modelcontextprotocol/swift-sdk](https://github.com/modelcontextprotocol/swift-sdk) | <Badge color="orange" shape="pill">Tier 3</Badge> |
18| <Icon icon="gem" size={24} />   [Ruby](https://ruby.sdk.modelcontextprotocol.io) | [modelcontextprotocol/ruby-sdk](https://github.com/modelcontextprotocol/ruby-sdk) | <Badge color="orange" shape="pill">Tier 3</Badge> |
19| <Icon icon="php" size={24} />   [PHP](https://php.sdk.modelcontextprotocol.io) | [modelcontextprotocol/php-sdk](https://github.com/modelcontextprotocol/php-sdk) | <Badge color="orange" shape="pill">Tier 3</Badge> |
20| <Icon icon="square-k" size={24} />   [Kotlin](https://kotlin.sdk.modelcontextprotocol.io) | [modelcontextprotocol/kotlin-sdk](https://github.com/modelcontextprotocol/kotlin-sdk) | <Badge color="orange" shape="pill">Tier 3</Badge> |
11|   [TypeScript](https://ts.sdk.modelcontextprotocol.io) | [modelcontextprotocol/typescript-sdk](https://github.com/modelcontextprotocol/typescript-sdk) | Tier 1 |
12|   [Python](https://py.sdk.modelcontextprotocol.io) | [modelcontextprotocol/python-sdk](https://github.com/modelcontextprotocol/python-sdk) | Tier 1 |
13|   [C#](https://csharp.sdk.modelcontextprotocol.io) | [modelcontextprotocol/csharp-sdk](https://github.com/modelcontextprotocol/csharp-sdk) | Tier 1 |
14|   [Go](https://go.sdk.modelcontextprotocol.io) | [modelcontextprotocol/go-sdk](https://github.com/modelcontextprotocol/go-sdk) | Tier 1 |
15|   [Java](https://java.sdk.modelcontextprotocol.io) | [modelcontextprotocol/java-sdk](https://github.com/modelcontextprotocol/java-sdk) | Tier 2 |
16|   [Rust](https://rust.sdk.modelcontextprotocol.io) | [modelcontextprotocol/rust-sdk](https://github.com/modelcontextprotocol/rust-sdk) | Tier 2 |
17|   Swift | [modelcontextprotocol/swift-sdk](https://github.com/modelcontextprotocol/swift-sdk) | Tier 3 |
18|   [Ruby](https://ruby.sdk.modelcontextprotocol.io) | [modelcontextprotocol/ruby-sdk](https://github.com/modelcontextprotocol/ruby-sdk) | Tier 3 |
19|   [PHP](https://php.sdk.modelcontextprotocol.io) | [modelcontextprotocol/php-sdk](https://github.com/modelcontextprotocol/php-sdk) | Tier 3 |
20|   [Kotlin](https://kotlin.sdk.modelcontextprotocol.io) | [modelcontextprotocol/kotlin-sdk](https://github.com/modelcontextprotocol/kotlin-sdk) | Tier 3 |
2121 
2222See [SDK Tiering System](/community/sdk-tiers) for details on what each tier means.
2323 
from line 36
3636 
3737Ready to start building with MCP? Choose your path:
3838 
39<CardGroup cols={2}>
40 <Card title="Build a Server" icon="server" href="/docs/2025-11-25/develop/build-server">
41 Learn how to create your first MCP server
42 </Card>
39> **[Build a Server](/docs/2025-11-25/develop/build-server)**
40>
41> Learn how to create your first MCP server
4342 
44 <Card title="Build a Client" icon="computer" href="/docs/2025-11-25/develop/build-client">
45 Create applications that connect to MCP servers
46 </Card>
47</CardGroup>
43> **[Build a Client](/docs/2025-11-25/develop/build-client)**
44>
45> Create applications that connect to MCP servers
4846 

docs/2025-11-25/tools/debugging Changed · +46 / -54 lines

from line 32
3232logged to stderr (standard error) will be captured by the host application
3333automatically.
3434 
35<Warning>
36 Local MCP servers should not log messages to stdout (standard out), as this
37 will interfere with protocol operation.
38</Warning>
35> [!WARNING]
36>
37> Local MCP servers should not log messages to stdout (standard out), as this
38> will interfere with protocol operation.
3939 
4040For servers using the
4141[Streamable HTTP transport](/specification/2025-11-25/basic/transports#streamable-http),
from line 48
4848For all [transports](/specification/2025-11-25/basic/transports), you can also
4949provide logging to the client by sending a log message notification:
5050 
51<CodeGroup>
52 ```python Python theme={null}
53 @server.tool()
54 async def my_tool(ctx: Context) -> str:
55 await ctx.session.send_log_message(
56 level="info",
57 data="Server started successfully",
58 )
59 return "done"
60 ```
51```python Python theme={null}
52@server.tool()
53async def my_tool(ctx: Context) -> str:
54 await ctx.session.send_log_message(
55 level="info",
56 data="Server started successfully",
57 )
58 return "done"
59```
6160 
62 ```typescript TypeScript theme={null}
63 await server.sendLoggingMessage({
64 level: "info",
65 data: "Server started successfully",
66 });
67 ```
68</CodeGroup>
61```typescript TypeScript theme={null}
62await server.sendLoggingMessage({
63 level: "info",
64 data: "Server started successfully",
65});
66```
6967 
7068MCP defines eight
7169[RFC 5424 severity levels](/specification/2025-11-25/server/utilities/logging#log-levels)
from line 189
191189hover over the **Connectors** menu to see connected servers and available
192190tools.
193191 
194<img src="https://mintcdn.com/mcp/zNouQwo2h8cbxlDS/images/available-mcp-tools.png?fit=max&auto=format&n=zNouQwo2h8cbxlDS&q=85&s=e2ace1ac88895a5fe30ebd8d01456bc3" alt="Available MCP tools" width="437" height="244" data-path="images/available-mcp-tools.png" />
192![Available MCP tools](https://mintcdn.com/mcp/zNouQwo2h8cbxlDS/images/available-mcp-tools.png?fit=max\&auto=format\&n=zNouQwo2h8cbxlDS\&q=85\&s=e2ace1ac88895a5fe30ebd8d01456bc3)
195193 
196194### Viewing logs
197195 
from line 198
200198* macOS: `~/Library/Logs/Claude`
201199* Windows: `%APPDATA%\Claude\logs`
202200 
203<CodeGroup>
204 ```bash macOS theme={null}
205 tail -n 20 -F ~/Library/Logs/Claude/mcp*.log
206 ```
201```bash macOS theme={null}
202tail -n 20 -F ~/Library/Logs/Claude/mcp*.log
203```
207204 
208 ```powershell Windows theme={null}
209 type "$env:AppData\Claude\logs\mcp*.log"
210 ```
211</CodeGroup>
205```powershell Windows theme={null}
206type "$env:AppData\Claude\logs\mcp*.log"
207```
212208 
213209The logs capture:
214210 
from line 220
224220 
2252211. Create a `developer_settings.json` file with `allowDevTools` set to true:
226222 
227<CodeGroup>
228 ```bash macOS theme={null}
229 echo '{"allowDevTools": true}' > ~/Library/Application\ Support/Claude/developer_settings.json
230 ```
223```bash macOS theme={null}
224echo '{"allowDevTools": true}' > ~/Library/Application\ Support/Claude/developer_settings.json
225```
231226 
232 ```powershell Windows theme={null}
233 '{"allowDevTools": true}' | Set-Content "$env:AppData\Claude\developer_settings.json"
234 ```
235</CodeGroup>
227```powershell Windows theme={null}
228'{"allowDevTools": true}' | Set-Content "$env:AppData\Claude\developer_settings.json"
229```
236230 
2372312. Open DevTools: `Command-Option-I` (macOS) or `Ctrl+Alt+I` (Windows)
238232 
from line 327
333327 
334328## Next steps
335329 
336<CardGroup cols={2}>
337 <Card title="MCP Inspector" icon="magnifying-glass" href="/docs/2025-11-25/tools/inspector">
338 Learn to use the MCP Inspector
339 </Card>
330> **[MCP Inspector](/docs/2025-11-25/tools/inspector)**
331>
332> Learn to use the MCP Inspector
340333 
341 <Card title="Build an MCP server" icon="code" href="/docs/2025-11-25/develop/build-server">
342 Walk through building a server from scratch
343 </Card>
334> **[Build an MCP server](/docs/2025-11-25/develop/build-server)**
335>
336> Walk through building a server from scratch
344337 
345 <Card title="Connect local servers" icon="plug" href="/docs/2025-11-25/develop/connect-local-servers">
346 Full claude\_desktop\_config.json reference and troubleshooting
347 </Card>
348</CardGroup>
338> **[Connect local servers](/docs/2025-11-25/develop/connect-local-servers)**
339>
340> Full claude\_desktop\_config.json reference and troubleshooting
349341 

docs/2025-11-25/tools/inspector Changed · +36 / -44 lines

from line 22
2222 
2323A common way to start server packages from [npm](https://npmjs.com) or [PyPI](https://pypi.org).
2424 
25<Tabs>
26 <Tab title="npm package">
27 ```bash theme={null}
28 npx -y @modelcontextprotocol/inspector npx <package-name> <args>
29 # For example
30 npx -y @modelcontextprotocol/inspector npx @modelcontextprotocol/server-filesystem /Users/username/Desktop
31 ```
32 </Tab>
25**npm package**
3326 
34 <Tab title="PyPI package">
35 ```bash theme={null}
36 npx @modelcontextprotocol/inspector uvx <package-name> <args>
37 # For example
38 npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git
39 ```
40 </Tab>
41</Tabs>
27```bash theme={null}
28npx -y @modelcontextprotocol/inspector npx <package-name> <args>
29# For example
30npx -y @modelcontextprotocol/inspector npx @modelcontextprotocol/server-filesystem /Users/username/Desktop
31```
4232 
33**PyPI package**
34 
35```bash theme={null}
36npx @modelcontextprotocol/inspector uvx <package-name> <args>
37# For example
38npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git
39```
40 
4341#### Inspecting locally developed servers
4442 
4543To inspect servers locally developed or downloaded as a repository, the most common
4644way is:
4745 
48<Tabs>
49 <Tab title="TypeScript">
50 ```bash theme={null}
51 npx @modelcontextprotocol/inspector node path/to/server/index.js args...
52 ```
53 </Tab>
46**TypeScript**
5447 
55 <Tab title="Python">
56 ```bash theme={null}
57 npx @modelcontextprotocol/inspector \
58 uv \
59 --directory path/to/server \
60 run \
61 package-name \
62 args...
63 ```
64 </Tab>
65</Tabs>
48```bash theme={null}
49npx @modelcontextprotocol/inspector node path/to/server/index.js args...
50```
6651 
52**Python**
53 
54```bash theme={null}
55npx @modelcontextprotocol/inspector \
56 uv \
57 --directory path/to/server \
58 run \
59 package-name \
60 args...
61```
62 
6763Please carefully read any attached README for the most accurate instructions.
6864 
6965## Feature overview
7066 
71<Frame caption="The MCP Inspector interface">
72 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/mcp-inspector.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=83b12e2a457c96ef4ad17c7357236290" width="2888" height="1761" data-path="images/mcp-inspector.png" />
73</Frame>
67![](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/mcp-inspector.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=83b12e2a457c96ef4ad17c7357236290)
7468 
7569The Inspector provides several features for interacting with your MCP server:
7670 
from line 123
129123 
130124## Next steps
131125 
132<CardGroup cols={2}>
133 <Card title="Inspector Repository" icon="github" href="https://github.com/modelcontextprotocol/inspector">
134 Check out the MCP Inspector source code
135 </Card>
126> **[Inspector Repository](https://github.com/modelcontextprotocol/inspector)**
127>
128> Check out the MCP Inspector source code
136129 
137 <Card title="Debugging Guide" icon="bug" href="/docs/2025-11-25/tools/debugging">
138 Learn about broader debugging strategies
139 </Card>
140</CardGroup>
130> **[Debugging Guide](/docs/2025-11-25/tools/debugging)**
131>
132> Learn about broader debugging strategies
141133 

docs/2025-11-25/tutorials/security/authorization Changed · +841 / -861 lines

The two sides of this change are more than 400 edits apart, too far apart to line up, so this is the differ's own diff of it and the words inside a line are not marked.

from line 16
1616* You're building for enterprise environments with strict access controls
1717* You want to implement rate limiting or usage tracking per user
1818 
19<Tip>
20 **Authorization for Local MCP Servers**
21 
22 For MCP servers using the [STDIO transport](/specification/2025-11-25/basic/transports#stdio), you can use environment-based credentials or credentials provided by third-party libraries embedded directly in the MCP server instead. Because a STDIO-built MCP server runs locally, it has access to a range of flexible options when it comes to acquiring user credentials that may or may not rely on in-browser authentication and authorization flows.
23 
24 OAuth flows, in turn, are designed for HTTP-based transports where the MCP server is remotely-hosted and the client uses OAuth to establish that a user is authorized to access said remote server.
25</Tip>
19> [!TIP]
20>
21> **Authorization for Local MCP Servers**
22>
23> For MCP servers using the [STDIO transport](/specification/2025-11-25/basic/transports#stdio), you can use environment-based credentials or credentials provided by third-party libraries embedded directly in the MCP server instead. Because a STDIO-built MCP server runs locally, it has access to a range of flexible options when it comes to acquiring user credentials that may or may not rely on in-browser authentication and authorization flows.
24>
25> OAuth flows, in turn, are designed for HTTP-based transports where the MCP server is remotely-hosted and the client uses OAuth to establish that a user is authorized to access said remote server.
2626 
2727## The Authorization Flow: Step by Step
2828 
2929Let's walk through what happens when a client wants to connect to your protected MCP server:
3030 
31<Steps>
32 <Step title="Initial Handshake">
33 When your MCP client first tries to connect, your server responds with a `401 Unauthorized` and tells the client where to find authorization information, captured in a [Protected Resource Metadata (PRM) document](https://datatracker.ietf.org/doc/html/rfc9728). The document is hosted by the MCP server, follows a predictable path pattern, and is provided to the client in the `resource_metadata` parameter within the `WWW-Authenticate` header.
34 
35 ```http theme={null}
36 HTTP/1.1 401 Unauthorized
37 WWW-Authenticate: Bearer realm="mcp",
38 resource_metadata="https://your-server.com/.well-known/oauth-protected-resource"
39 ```
40 
41 This tells the client that authorization is required for the MCP server and where to get the necessary information to kickstart the authorization flow.
42 </Step>
43 
44 <Step title="Protected Resource Metadata Discovery">
45 With the URI pointer to the PRM document, the client will fetch the metadata to learn about the authorization server, supported scopes, and other resource information. The data is typically encapsulated in a JSON blob, similar to the one below.
46 
47 ```json theme={null}
48 {
49 "resource": "https://your-server.com/mcp",
50 "authorization_servers": ["https://auth.your-server.com"],
51 "scopes_supported": ["mcp:tools", "mcp:resources"]
52 }
53 ```
54 
55 You can see a more comprehensive example in [RFC 9728 Section 3.2](https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata-r).
56 </Step>
57 
58 <Step title="Authorization Server Discovery">
59 Next, the client discovers what the authorization server can do by fetching its metadata. If the PRM document lists more than one authorization server, the client can decide which one to use.
60 
61 With an authorization server selected, the client will then construct a standard metadata URI and issue a request to the [OpenID Connect (OIDC) Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) or [OAuth 2.0 Auth Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) endpoints (depending on authorization server support)
62 and retrieve another set of metadata properties that will allow it to know the endpoints it needs to complete the authorization flow.
63 
64 ```json theme={null}
65 {
66 "issuer": "https://auth.your-server.com",
67 "authorization_endpoint": "https://auth.your-server.com/authorize",
68 "token_endpoint": "https://auth.your-server.com/token",
69 "registration_endpoint": "https://auth.your-server.com/register"
70 }
71 ```
72 </Step>
73 
74 <Step title="Client Registration">
75 With all the metadata out of the way, the client now needs to make sure that it's registered with the authorization server. This can be done in two ways.
76 
77 First, the client can be **pre-registered** with a given authorization server, in which case it can have embedded client registration information that it uses to complete the authorization flow.
78 
79 Alternatively, the client can use **Dynamic Client Registration** (DCR) to dynamically register itself with the authorization server. The latter scenario requires the authorization server to support DCR. If the authorization server does support DCR, the client will send a request to the `registration_endpoint` with its information:
80 
81 ```json theme={null}
82 {
83 "client_name": "My MCP Client",
84 "redirect_uris": ["http://localhost:3000/callback"],
85 "grant_types": ["authorization_code", "refresh_token"],
86 "response_types": ["code"]
87 }
88 ```
89 
90 If the registration succeeds, the authorization server will return a JSON blob with client registration information.
91 
92 <Tip>
93 **No DCR or Pre-Registration**
94 
95 In case an MCP client connects to an MCP server that doesn't use an authorization server that supports DCR and the client is not pre-registered with said authorization server, it's the responsibility of the client developer to provide an affordance for the end-user to enter client information manually.
96 </Tip>
97 </Step>
98 
99 <Step title="User Authorization">
100 The client will now need to open a browser to the `/authorize` endpoint, where the user can log in and grant the required permissions. The authorization server will then redirect back to the client with an authorization code that the client exchanges for tokens:
101 
102 ```json theme={null}
103 {
104 "access_token": "eyJhbGciOiJSUzI1NiIs...",
105 "refresh_token": "def502...",
106 "token_type": "Bearer",
107 "expires_in": 3600
108 }
109 ```
110 
111 The access token is what the client will use to authenticate requests to the MCP server. This step follows standard [OAuth 2.1 authorization code with PKCE](https://oauth.net/2/grant-types/authorization-code/) conventions.
112 </Step>
113 
114 <Step title="Making Authenticated Requests">
115 Finally, the client can make requests to your MCP server using the access token embedded in the `Authorization` header:
116 
117 ```http theme={null}
118 GET /mcp HTTP/1.1
119 Host: your-server.com
120 Authorization: Bearer eyJhbGciOiJSUzI1NiIs...
121 ```
122 
123 The MCP server will need to validate the token and process the request if the token is valid and has the required permissions.
124 </Step>
125</Steps>
31**1. Initial Handshake**
32 
33When your MCP client first tries to connect, your server responds with a `401 Unauthorized` and tells the client where to find authorization information, captured in a [Protected Resource Metadata (PRM) document](https://datatracker.ietf.org/doc/html/rfc9728). The document is hosted by the MCP server, follows a predictable path pattern, and is provided to the client in the `resource_metadata` parameter within the `WWW-Authenticate` header.
34 
35```http theme={null}
36HTTP/1.1 401 Unauthorized
37WWW-Authenticate: Bearer realm="mcp",
38 resource_metadata="https://your-server.com/.well-known/oauth-protected-resource"
39```
40 
41This tells the client that authorization is required for the MCP server and where to get the necessary information to kickstart the authorization flow.
42 
43**2. Protected Resource Metadata Discovery**
44 
45With the URI pointer to the PRM document, the client will fetch the metadata to learn about the authorization server, supported scopes, and other resource information. The data is typically encapsulated in a JSON blob, similar to the one below.
46 
47```json theme={null}
48{
49 "resource": "https://your-server.com/mcp",
50 "authorization_servers": ["https://auth.your-server.com"],
51 "scopes_supported": ["mcp:tools", "mcp:resources"]
52}
53```
54 
55You can see a more comprehensive example in [RFC 9728 Section 3.2](https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata-r).
56 
57**3. Authorization Server Discovery**
58 
59Next, the client discovers what the authorization server can do by fetching its metadata. If the PRM document lists more than one authorization server, the client can decide which one to use.
60 
61With an authorization server selected, the client will then construct a standard metadata URI and issue a request to the [OpenID Connect (OIDC) Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) or [OAuth 2.0 Auth Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414) endpoints (depending on authorization server support)
62and retrieve another set of metadata properties that will allow it to know the endpoints it needs to complete the authorization flow.
63 
64```json theme={null}
65{
66 "issuer": "https://auth.your-server.com",
67 "authorization_endpoint": "https://auth.your-server.com/authorize",
68 "token_endpoint": "https://auth.your-server.com/token",
69 "registration_endpoint": "https://auth.your-server.com/register"
70}
71```
72 
73**4. Client Registration**
74 
75With all the metadata out of the way, the client now needs to make sure that it's registered with the authorization server. This can be done in two ways.
76 
77First, the client can be **pre-registered** with a given authorization server, in which case it can have embedded client registration information that it uses to complete the authorization flow.
78 
79Alternatively, the client can use **Dynamic Client Registration** (DCR) to dynamically register itself with the authorization server. The latter scenario requires the authorization server to support DCR. If the authorization server does support DCR, the client will send a request to the `registration_endpoint` with its information:
80 
81```json theme={null}
82{
83 "client_name": "My MCP Client",
84 "redirect_uris": ["http://localhost:3000/callback"],
85 "grant_types": ["authorization_code", "refresh_token"],
86 "response_types": ["code"]
87}
88```
89 
90If the registration succeeds, the authorization server will return a JSON blob with client registration information.
91 
92> [!TIP]
93>
94> **No DCR or Pre-Registration**
95>
96> In case an MCP client connects to an MCP server that doesn't use an authorization server that supports DCR and the client is not pre-registered with said authorization server, it's the responsibility of the client developer to provide an affordance for the end-user to enter client information manually.
97 
98**5. User Authorization**
99 
100The client will now need to open a browser to the `/authorize` endpoint, where the user can log in and grant the required permissions. The authorization server will then redirect back to the client with an authorization code that the client exchanges for tokens:
101 
102```json theme={null}
103{
104 "access_token": "eyJhbGciOiJSUzI1NiIs...",
105 "refresh_token": "def502...",
106 "token_type": "Bearer",
107 "expires_in": 3600
108}
109```
110 
111The access token is what the client will use to authenticate requests to the MCP server. This step follows standard [OAuth 2.1 authorization code with PKCE](https://oauth.net/2/grant-types/authorization-code/) conventions.
112 
113**6. Making Authenticated Requests**
114 
115Finally, the client can make requests to your MCP server using the access token embedded in the `Authorization` header:
116 
117```http theme={null}
118GET /mcp HTTP/1.1
119Host: your-server.com
120Authorization: Bearer eyJhbGciOiJSUzI1NiIs...
121```
122 
123The MCP server will need to validate the token and process the request if the token is valid and has the required permissions.
126124 
127125## Implementation Example
128126 
from line 138
140138 
141139This command will pull the Keycloak container image locally and bootstrap the basic configuration. It will run on port `8080` and have an `admin` user with `admin` password.
142140 
143<Warning>
144 **Not for Production**
145 
146 The configuration above may be suitable for testing and experimentation; however, you should never use it in production. Refer to the [Configuring Keycloak for production](https://www.keycloak.org/server/configuration-production) guide for additional details on how to deploy the authorization server for scenarios that require reliability, security, and high availability.
147</Warning>
141> [!WARNING]
142>
143> **Not for Production**
144>
145> The configuration above may be suitable for testing and experimentation; however, you should never use it in production. Refer to the [Configuring Keycloak for production](https://www.keycloak.org/server/configuration-production) guide for additional details on how to deploy the authorization server for scenarios that require reliability, security, and high availability.
148146 
149147You will be able to access the Keycloak authorization server from your browser at `http://localhost:8080`.
150148 
151<Frame>
152 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-browser.png?fit=max&auto=format&n=sAd4SGUO-cEUqgzn&q=85&s=cba689d986e113cbe937d732ac0558b6" alt="Keycloak admin dashboard authentication dialog." width="1834" height="1450" data-path="images/tutorial-authorization/keycloak-browser.png" />
153</Frame>
149![Keycloak admin dashboard authentication dialog.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-browser.png?fit=max\&auto=format\&n=sAd4SGUO-cEUqgzn\&q=85\&s=cba689d986e113cbe937d732ac0558b6)
154150 
155151When running with the default configuration, Keycloak will already support many of the capabilities that we need for MCP servers, including Dynamic Client Registration. You can check this by looking at the OIDC configuration, available at:
156152 
from line 158
162158 
163159Go to **Client scopes** in the Keycloak dashboard and create a new `mcp:tools` scope. We will use this to access all of the tools on our MCP server.
164160 
165<Frame>
166 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-scopes.png?fit=max&auto=format&n=sAd4SGUO-cEUqgzn&q=85&s=3cd49dc2e070027609ae495751e0db58" alt="Configuring Keycloak scopes." width="1999" height="1710" data-path="images/tutorial-authorization/keycloak-scopes.png" />
167</Frame>
161![Configuring Keycloak scopes.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-scopes.png?fit=max\&auto=format\&n=sAd4SGUO-cEUqgzn\&q=85\&s=3cd49dc2e070027609ae495751e0db58)
168162 
169163After creating the scope, make sure that you assign its type to **Default** and have flipped the **Include in token scope** switch, as this will be needed for token validation.
170164 
from line 166
172166 
173167To do this, open your `mcp:tools` client scope and click on **Mappers**, followed by **Configure a new mapper**. Select **Audience**.
174168 
175<Frame>
176 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/scope-add-audience.gif?s=6ea9cf20c397f4c79c491c2e39019272" alt="Configuring an audience for a token in Keycloak." width="1080" height="921" data-path="images/tutorial-authorization/scope-add-audience.gif" />
177</Frame>
169![Configuring an audience for a token in Keycloak.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/scope-add-audience.gif?s=6ea9cf20c397f4c79c491c2e39019272)
178170 
179171For **Name**, use `audience-config`. Add a value for **Included Custom Audience**, set to `http://localhost:3000`. This will be the URI of our test server.
180172 
181<Warning>
182 **Not for Production**
183 
184 The audience configuration above is meant for testing. For production scenarios, additional set-up and configuration will be required to ensure that audiences are properly constrained for issued tokens. Specifically, the audience needs to be based on the resource parameter passed from the client, not a fixed value.
185</Warning>
173> [!WARNING]
174>
175> **Not for Production**
176>
177> The audience configuration above is meant for testing. For production scenarios, additional set-up and configuration will be required to ensure that audiences are properly constrained for issued tokens. Specifically, the audience needs to be based on the resource parameter passed from the client, not a fixed value.
186178 
187179Now, navigate to **Clients**, then **Client registration**, and then **Trusted Hosts**. Disable the **Client URIs Must Match** setting and add the hosts from which you're testing. You can get your current host IP by running the `ifconfig` command on Linux or macOS, or `ipconfig` on Windows. You can see the IP address you need to add by looking at the keycloak logs for a line that looks like `Failed to verify remote host : 192.168.215.1`. Check that the IP address is associated with your host. This may be for a bridge network depending on your docker setup.
188180 
189<Frame>
190 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-client.gif?s=b5d40b36a5f1ea1e818821bb8ea77f6b" alt="Setting up client registration details in Keycloak." width="1199" height="1027" data-path="images/tutorial-authorization/keycloak-client.gif" />
191</Frame>
192 
193<Warning>
194 **Getting the Host**
195 
196 If you are running Keycloak from a container, you will also be able to see the host IP from the Terminal in the container logs.
197</Warning>
181![Setting up client registration details in Keycloak.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-client.gif?s=b5d40b36a5f1ea1e818821bb8ea77f6b)
182 
183> [!WARNING]
184>
185> **Getting the Host**
186>
187> If you are running Keycloak from a container, you will also be able to see the host IP from the Terminal in the container logs.
198188 
199189Lastly, we need to register a new client that we can use with the **MCP server itself** to talk to Keycloak for things like [token introspection](https://oauth.net/2/token-introspection/). To do that:
200190 
from line 198
208198 
209199When you open the client details, go to **Credentials** and take note of the **Client Secret**.
210200 
211<Frame>
212 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-client-auth.gif?s=7152c41a5746994fd399024bc4659e40" alt="Creating a new client in Keycloak." width="1200" height="1023" data-path="images/tutorial-authorization/keycloak-client-auth.gif" />
213</Frame>
214 
215<Warning>
216 **Handling Secrets**
217 
218 Never embed client credentials directly in your code. We recommend using environment variables or specialized solutions for secret storage.
219</Warning>
201![Creating a new client in Keycloak.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-client-auth.gif?s=7152c41a5746994fd399024bc4659e40)
202 
203> [!WARNING]
204>
205> **Handling Secrets**
206>
207> Never embed client credentials directly in your code. We recommend using environment variables or specialized solutions for secret storage.
220208 
221209With Keycloak configured, every time the authorization flow is triggered, your MCP server will receive a token like this:
222210 
from line 234
246234}.[Signature]
247235```
248236 
249<Warning>
250 **Embedded Audience**
251 
252 Notice the `aud` claim embedded in the token - it's currently set to be the URI of the test MCP server and it's inferred from the scope that we've previously configured. This will be important in our implementation to validate.
253</Warning>
237> [!WARNING]
238>
239> **Embedded Audience**
240>
241> Notice the `aud` claim embedded in the token - it's currently set to be the URI of the test MCP server and it's inferred from the scope that we've previously configured. This will be important in our implementation to validate.
254242 
255243### MCP Server Setup
256244 
from line 246
258246 
259247For our testing purposes, we will create an extremely simple MCP server that exposes two tools - one for addition and another for multiplication. The server will require authorization to access these.
260248 
261<Tabs>
262 <Tab title="TypeScript">
263 You can see the complete TypeScript project in the [sample repository](https://github.com/localden/min-ts-mcp-auth).
264 
265 Prior to running the code below, ensure that you have a `.env` file with the following content:
266 
267 ```env theme={null}
268 # Server host/port
269 HOST=localhost
270 PORT=3000
271 
272 # Auth server location
273 AUTH_HOST=localhost
274 AUTH_PORT=8080
275 AUTH_REALM=master
276 
277 # Keycloak OAuth client credentials
278 OAUTH_CLIENT_ID=<YOUR_SERVER_CLIENT_ID>
279 OAUTH_CLIENT_SECRET=<YOUR_SERVER_CLIENT_SECRET>
280 ```
281 
282 `OAUTH_CLIENT_ID` and `OAUTH_CLIENT_SECRET` are associated with the MCP server client we created earlier.
283 
284 In addition to implementing the MCP authorization specification, the server below also does token introspection via Keycloak to make sure that the token it receives from the client is valid. It also implements basic logging to allow you to easily diagnose any issues.
285 
286 ```typescript theme={null}
287 import "dotenv/config";
288 import express from "express";
289 import { randomUUID } from "node:crypto";
290 import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
291 import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
292 import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
293 import { z } from "zod";
294 import cors from "cors";
295 import {
296 mcpAuthMetadataRouter,
297 getOAuthProtectedResourceMetadataUrl,
298 } from "@modelcontextprotocol/sdk/server/auth/router.js";
299 import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
300 import { OAuthMetadata } from "@modelcontextprotocol/sdk/shared/auth.js";
301 import { checkResourceAllowed } from "@modelcontextprotocol/sdk/shared/auth-utils.js";
302 const CONFIG = {
303 host: process.env.HOST || "localhost",
304 port: Number(process.env.PORT) || 3000,
305 auth: {
306 host: process.env.AUTH_HOST || process.env.HOST || "localhost",
307 port: Number(process.env.AUTH_PORT) || 8080,
308 realm: process.env.AUTH_REALM || "master",
309 clientId: process.env.OAUTH_CLIENT_ID || "mcp-server",
310 clientSecret: process.env.OAUTH_CLIENT_SECRET || "",
311 },
312 };
313 
314 function createOAuthUrls() {
315 const authBaseUrl = new URL(
316 `http://${CONFIG.auth.host}:${CONFIG.auth.port}/realms/${CONFIG.auth.realm}/`,
249**TypeScript**
250 
251You can see the complete TypeScript project in the [sample repository](https://github.com/localden/min-ts-mcp-auth).
252 
253Prior to running the code below, ensure that you have a `.env` file with the following content:
254 
255```env theme={null}
256# Server host/port
257HOST=localhost
258PORT=3000
259 
260# Auth server location
261AUTH_HOST=localhost
262AUTH_PORT=8080
263AUTH_REALM=master
264 
265# Keycloak OAuth client credentials
266OAUTH_CLIENT_ID=<YOUR_SERVER_CLIENT_ID>
267OAUTH_CLIENT_SECRET=<YOUR_SERVER_CLIENT_SECRET>
268```
269 
270`OAUTH_CLIENT_ID` and `OAUTH_CLIENT_SECRET` are associated with the MCP server client we created earlier.
271 
272In addition to implementing the MCP authorization specification, the server below also does token introspection via Keycloak to make sure that the token it receives from the client is valid. It also implements basic logging to allow you to easily diagnose any issues.
273 
274```typescript theme={null}
275import "dotenv/config";
276import express from "express";
277import { randomUUID } from "node:crypto";
278import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
279import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
280import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
281import { z } from "zod";
282import cors from "cors";
283import {
284 mcpAuthMetadataRouter,
285 getOAuthProtectedResourceMetadataUrl,
286} from "@modelcontextprotocol/sdk/server/auth/router.js";
287import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
288import { OAuthMetadata } from "@modelcontextprotocol/sdk/shared/auth.js";
289import { checkResourceAllowed } from "@modelcontextprotocol/sdk/shared/auth-utils.js";
290const CONFIG = {
291 host: process.env.HOST || "localhost",
292 port: Number(process.env.PORT) || 3000,
293 auth: {
294 host: process.env.AUTH_HOST || process.env.HOST || "localhost",
295 port: Number(process.env.AUTH_PORT) || 8080,
296 realm: process.env.AUTH_REALM || "master",
297 clientId: process.env.OAUTH_CLIENT_ID || "mcp-server",
298 clientSecret: process.env.OAUTH_CLIENT_SECRET || "",
299 },
300};
301 
302function createOAuthUrls() {
303 const authBaseUrl = new URL(
304 `http://${CONFIG.auth.host}:${CONFIG.auth.port}/realms/${CONFIG.auth.realm}/`,
305 );
306 return {
307 issuer: authBaseUrl.toString(),
308 introspection_endpoint: new URL(
309 "protocol/openid-connect/token/introspect",
310 authBaseUrl,
311 ).toString(),
312 authorization_endpoint: new URL(
313 "protocol/openid-connect/auth",
314 authBaseUrl,
315 ).toString(),
316 token_endpoint: new URL(
317 "protocol/openid-connect/token",
318 authBaseUrl,
319 ).toString(),
320 };
321}
322 
323function createRequestLogger() {
324 return (req: any, res: any, next: any) => {
325 const start = Date.now();
326 res.on("finish", () => {
327 const ms = Date.now() - start;
328 console.log(
329 `${req.method} ${req.originalUrl} -> ${res.statusCode} ${ms}ms`,
317330 );
318 return {
319 issuer: authBaseUrl.toString(),
320 introspection_endpoint: new URL(
321 "protocol/openid-connect/token/introspect",
322 authBaseUrl,
323 ).toString(),
324 authorization_endpoint: new URL(
325 "protocol/openid-connect/auth",
326 authBaseUrl,
327 ).toString(),
328 token_endpoint: new URL(
329 "protocol/openid-connect/token",
330 authBaseUrl,
331 ).toString(),
332 };
331 });
332 next();
333 };
334}
335 
336const app = express();
337 
338app.use(
339 express.json({
340 verify: (req: any, _res, buf) => {
341 req.rawBody = buf?.toString() ?? "";
342 },
343 }),
344);
345 
346app.use(
347 cors({
348 origin: "*",
349 exposedHeaders: ["Mcp-Session-Id"],
350 }),
351);
352 
353app.use(createRequestLogger());
354 
355const mcpServerUrl = new URL(`http://${CONFIG.host}:${CONFIG.port}`);
356const oauthUrls = createOAuthUrls();
357 
358const oauthMetadata: OAuthMetadata = {
359 ...oauthUrls,
360 response_types_supported: ["code"],
361};
362 
363const tokenVerifier = {
364 verifyAccessToken: async (token: string) => {
365 const endpoint = oauthMetadata.introspection_endpoint;
366 
367 if (!endpoint) {
368 console.error("[auth] no introspection endpoint in metadata");
369 throw new Error("No token verification endpoint available in metadata");
333370 }
334371 
335 function createRequestLogger() {
336 return (req: any, res: any, next: any) => {
337 const start = Date.now();
338 res.on("finish", () => {
339 const ms = Date.now() - start;
340 console.log(
341 `${req.method} ${req.originalUrl} -> ${res.statusCode} ${ms}ms`,
342 );
343 });
344 next();
345 };
372 const params = new URLSearchParams({
373 token: token,
374 client_id: CONFIG.auth.clientId,
375 });
376 
377 if (CONFIG.auth.clientSecret) {
378 params.set("client_secret", CONFIG.auth.clientSecret);
346379 }
347380 
348 const app = express();
349 
350 app.use(
351 express.json({
352 verify: (req: any, _res, buf) => {
353 req.rawBody = buf?.toString() ?? "";
381 let response: Response;
382 try {
383 response = await fetch(endpoint, {
384 method: "POST",
385 headers: {
386 "Content-Type": "application/x-www-form-urlencoded",
354387 },
388 body: params.toString(),
389 });
390 } catch (e) {
391 console.error("[auth] introspection fetch threw", e);
392 throw e;
393 }
394 
395 if (!response.ok) {
396 const txt = await response.text();
397 console.error("[auth] introspection non-OK", { status: response.status });
398 
399 try {
400 const obj = JSON.parse(txt);
401 console.log(JSON.stringify(obj, null, 2));
402 } catch {
403 console.error(txt);
404 }
405 throw new Error(`Invalid or expired token: ${txt}`);
406 }
407 
408 let data: any;
409 try {
410 data = await response.json();
411 } catch (e) {
412 const txt = await response.text();
413 console.error("[auth] failed to parse introspection JSON", {
414 error: String(e),
415 body: txt,
416 });
417 throw e;
418 }
419 
420 if (data.active === false) {
421 throw new Error("Inactive token");
422 }
423 
424 if (!data.aud) {
425 throw new Error("Resource indicator (aud) missing");
426 }
427 
428 const audiences: string[] = Array.isArray(data.aud) ? data.aud : [data.aud];
429 const allowed = audiences.some((a) =>
430 checkResourceAllowed({
431 requestedResource: a,
432 configuredResource: mcpServerUrl,
355433 }),
356434 );
357 
358 app.use(
359 cors({
360 origin: "*",
361 exposedHeaders: ["Mcp-Session-Id"],
362 }),
363 );
364 
365 app.use(createRequestLogger());
366 
367 const mcpServerUrl = new URL(`http://${CONFIG.host}:${CONFIG.port}`);
368 const oauthUrls = createOAuthUrls();
369 
370 const oauthMetadata: OAuthMetadata = {
371 ...oauthUrls,
372 response_types_supported: ["code"],
435 if (!allowed) {
436 throw new Error(
437 `None of the provided audiences are allowed. Expected ${mcpServerUrl}, got: ${audiences.join(", ")}`,
438 );
439 }
440 
441 return {
442 token,
443 clientId: data.client_id,
444 scopes: data.scope ? data.scope.split(" ") : [],
445 expiresAt: data.exp,
373446 };
374 
375 const tokenVerifier = {
376 verifyAccessToken: async (token: string) => {
377 const endpoint = oauthMetadata.introspection_endpoint;
378 
379 if (!endpoint) {
380 console.error("[auth] no introspection endpoint in metadata");
381 throw new Error("No token verification endpoint available in metadata");
447 },
448};
449app.use(
450 mcpAuthMetadataRouter({
451 oauthMetadata,
452 resourceServerUrl: mcpServerUrl,
453 scopesSupported: ["mcp:tools"],
454 resourceName: "MCP Demo Server",
455 }),
456);
457 
458const authMiddleware = requireBearerAuth({
459 verifier: tokenVerifier,
460 requiredScopes: [],
461 resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl),
462});
463 
464const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {};
465 
466function createMcpServer() {
467 const server = new McpServer({
468 name: "example-server",
469 version: "1.0.0",
470 });
471 
472 server.registerTool(
473 "add",
474 {
475 title: "Addition Tool",
476 description: "Add two numbers together",
477 inputSchema: {
478 a: z.number().describe("First number to add"),
479 b: z.number().describe("Second number to add"),
480 },
481 },
482 async ({ a, b }) => ({
483 content: [{ type: "text", text: `${a} + ${b} = ${a + b}` }],
484 }),
485 );
486 
487 server.registerTool(
488 "multiply",
489 {
490 title: "Multiplication Tool",
491 description: "Multiply two numbers together",
492 inputSchema: {
493 x: z.number().describe("First number to multiply"),
494 y: z.number().describe("Second number to multiply"),
495 },
496 },
497 async ({ x, y }) => ({
498 content: [{ type: "text", text: `${x} × ${y} = ${x * y}` }],
499 }),
500 );
501 
502 return server;
503}
504 
505const mcpPostHandler = async (req: express.Request, res: express.Response) => {
506 const sessionId = req.headers["mcp-session-id"] as string | undefined;
507 let transport: StreamableHTTPServerTransport;
508 
509 if (sessionId && transports[sessionId]) {
510 transport = transports[sessionId];
511 } else if (!sessionId && isInitializeRequest(req.body)) {
512 transport = new StreamableHTTPServerTransport({
513 sessionIdGenerator: () => randomUUID(),
514 onsessioninitialized: (sessionId) => {
515 transports[sessionId] = transport;
516 },
517 });
518 
519 transport.onclose = () => {
520 if (transport.sessionId) {
521 delete transports[transport.sessionId];
522 }
523 };
524 
525 const server = createMcpServer();
526 await server.connect(transport);
527 } else {
528 res.status(400).json({
529 jsonrpc: "2.0",
530 error: {
531 code: -32000,
532 message: "Bad Request: No valid session ID provided",
533 },
534 id: null,
535 });
536 return;
537 }
538 
539 await transport.handleRequest(req, res, req.body);
540};
541 
542const handleSessionRequest = async (
543 req: express.Request,
544 res: express.Response,
545) => {
546 const sessionId = req.headers["mcp-session-id"] as string | undefined;
547 if (!sessionId || !transports[sessionId]) {
548 res.status(400).send("Invalid or missing session ID");
549 return;
550 }
551 
552 const transport = transports[sessionId];
553 await transport.handleRequest(req, res);
554};
555 
556app.post("/", authMiddleware, mcpPostHandler);
557app.get("/", authMiddleware, handleSessionRequest);
558app.delete("/", authMiddleware, handleSessionRequest);
559 
560app.listen(CONFIG.port, CONFIG.host, () => {
561 console.log(`🚀 MCP Server running on ${mcpServerUrl.origin}`);
562 console.log(`📡 MCP endpoint available at ${mcpServerUrl.origin}`);
563 console.log(
564 `🔐 OAuth metadata available at ${getOAuthProtectedResourceMetadataUrl(mcpServerUrl)}`,
565 );
566});
567```
568 
569When you run the server, you can add it to your MCP client, such as Visual Studio Code, by providing the MCP server endpoint.
570 
571For more details about implementing MCP servers in TypeScript, refer to the [TypeScript SDK documentation](https://github.com/modelcontextprotocol/typescript-sdk).
572 
573**Python**
574 
575You can see the complete Python project in the [sample repository](https://github.com/modelcontextprotocol/python-sdk/tree/main/examples/servers/simple-auth).
576 
577To simplify our authorization interaction, in Python scenarios we rely on [FastMCP](https://gofastmcp.com/getting-started/welcome). Many of the conventions around authorization, like the endpoints and token validation logic, are consistent across languages, but some offer simpler ways of integrating them in production scenarios.
578 
579Prior to writing the actual server, we need to set up our configuration in `config.py` - the contents are entirely based on your local server setup:
580 
581```python theme={null}
582"""Configuration settings for the MCP auth server."""
583 
584import os
585from typing import Optional
586 
587 
588class Config:
589 """Configuration class that loads from environment variables with sensible defaults."""
590 
591 # Server settings
592 HOST: str = os.getenv("HOST", "localhost")
593 PORT: int = int(os.getenv("PORT", "3000"))
594 
595 # Auth server settings
596 AUTH_HOST: str = os.getenv("AUTH_HOST", "localhost")
597 AUTH_PORT: int = int(os.getenv("AUTH_PORT", "8080"))
598 AUTH_REALM: str = os.getenv("AUTH_REALM", "master")
599 
600 # OAuth client settings
601 OAUTH_CLIENT_ID: str = os.getenv("OAUTH_CLIENT_ID", "mcp-server")
602 OAUTH_CLIENT_SECRET: str = os.getenv("OAUTH_CLIENT_SECRET", "UO3rmozkFFkXr0QxPTkzZ0LMXDidIikB")
603 
604 # Server settings
605 MCP_SCOPE: str = os.getenv("MCP_SCOPE", "mcp:tools")
606 OAUTH_STRICT: bool = os.getenv("OAUTH_STRICT", "false").lower() in ("true", "1", "yes")
607 TRANSPORT: str = os.getenv("TRANSPORT", "streamable-http")
608 
609 @property
610 def server_url(self) -> str:
611 """Build the server URL."""
612 return f"http://{self.HOST}:{self.PORT}"
613 
614 @property
615 def auth_base_url(self) -> str:
616 """Build the auth server base URL."""
617 return f"http://{self.AUTH_HOST}:{self.AUTH_PORT}/realms/{self.AUTH_REALM}/"
618 
619 def validate(self) -> None:
620 """Validate configuration."""
621 if self.TRANSPORT not in ["sse", "streamable-http"]:
622 raise ValueError(f"Invalid transport: {self.TRANSPORT}. Must be 'sse' or 'streamable-http'")
623 
624 
625# Global configuration instance
626config = Config()
627 
628```
629 
630The server implementation is as follows:
631 
632```python theme={null}
633import datetime
634import logging
635from typing import Any
636 
637from pydantic import AnyHttpUrl
638 
639from mcp.server.auth.settings import AuthSettings
640from mcp.server.fastmcp.server import FastMCP
641 
642from .config import config
643from .token_verifier import IntrospectionTokenVerifier
644 
645logger = logging.getLogger(__name__)
646 
647 
648def create_oauth_urls() -> dict[str, str]:
649 """Create OAuth URLs based on configuration (Keycloak-style)."""
650 from urllib.parse import urljoin
651 
652 auth_base_url = config.auth_base_url
653 
654 return {
655 "issuer": auth_base_url,
656 "introspection_endpoint": urljoin(auth_base_url, "protocol/openid-connect/token/introspect"),
657 "authorization_endpoint": urljoin(auth_base_url, "protocol/openid-connect/auth"),
658 "token_endpoint": urljoin(auth_base_url, "protocol/openid-connect/token"),
659 }
660 
661 
662def create_server() -> FastMCP:
663 """Create and configure the FastMCP server."""
664 
665 config.validate()
666 
667 oauth_urls = create_oauth_urls()
668 
669 token_verifier = IntrospectionTokenVerifier(
670 introspection_endpoint=oauth_urls["introspection_endpoint"],
671 server_url=config.server_url,
672 client_id=config.OAUTH_CLIENT_ID,
673 client_secret=config.OAUTH_CLIENT_SECRET,
674 )
675 
676 app = FastMCP(
677 name="MCP Resource Server",
678 instructions="Resource Server that validates tokens via Authorization Server introspection",
679 host=config.HOST,
680 port=config.PORT,
681 debug=True,
682 streamable_http_path="/",
683 token_verifier=token_verifier,
684 auth=AuthSettings(
685 issuer_url=AnyHttpUrl(oauth_urls["issuer"]),
686 required_scopes=[config.MCP_SCOPE],
687 resource_server_url=AnyHttpUrl(config.server_url),
688 ),
689 )
690 
691 @app.tool()
692 async def add_numbers(a: float, b: float) -> dict[str, Any]:
693 """
694 Add two numbers together.
695 This tool demonstrates basic arithmetic operations with OAuth authentication.
696 
697 Args:
698 a: The first number to add
699 b: The second number to add
700 """
701 result = a + b
702 return {
703 "operation": "addition",
704 "operand_a": a,
705 "operand_b": b,
706 "result": result,
707 "timestamp": datetime.datetime.now().isoformat()
382708 }
383709 
384 const params = new URLSearchParams({
385 token: token,
386 client_id: CONFIG.auth.clientId,
387 });
388 
389 if (CONFIG.auth.clientSecret) {
390 params.set("client_secret", CONFIG.auth.clientSecret);
710 @app.tool()
711 async def multiply_numbers(x: float, y: float) -> dict[str, Any]:
712 """
713 Multiply two numbers together.
714 This tool demonstrates basic arithmetic operations with OAuth authentication.
715 
716 Args:
717 x: The first number to multiply
718 y: The second number to multiply
719 """
720 result = x * y
721 return {
722 "operation": "multiplication",
723 "operand_x": x,
724 "operand_y": y,
725 "result": result,
726 "timestamp": datetime.datetime.now().isoformat()
391727 }
392728 
393 let response: Response;
394 try {
395 response = await fetch(endpoint, {
396 method: "POST",
397 headers: {
398 "Content-Type": "application/x-www-form-urlencoded",
399 },
400 body: params.toString(),
401 });
402 } catch (e) {
403 console.error("[auth] introspection fetch threw", e);
404 throw e;
729 return app
730 
731 
732def main() -> int:
733 """
734 Run the MCP Resource Server.
735 
736 This server:
737 - Provides RFC 9728 Protected Resource Metadata
738 - Validates tokens via Authorization Server introspection
739 - Serves MCP tools requiring authentication
740 
741 Configuration is loaded from config.py and environment variables.
742 """
743 logging.basicConfig(level=logging.INFO)
744 
745 try:
746 config.validate()
747 oauth_urls = create_oauth_urls()
748 
749 except ValueError as e:
750 logger.error("Configuration error: %s", e)
751 return 1
752 
753 try:
754 mcp_server = create_server()
755 
756 logger.info("Starting MCP Server on %s:%s", config.HOST, config.PORT)
757 logger.info("Authorization Server: %s", oauth_urls["issuer"])
758 logger.info("Transport: %s", config.TRANSPORT)
759 
760 mcp_server.run(transport=config.TRANSPORT)
761 return 0
762 
763 except Exception:
764 logger.exception("Server error")
765 return 1
766 
767 
768if __name__ == "__main__":
769 exit(main())
770```
771 
772Lastly, the token verification logic is delegated entirely to `token_verifier.py`, ensuring that we can use the Keycloak introspection endpoint to verify the validity of any credential artifacts
773 
774```python theme={null}
775"""Token verifier implementation using OAuth 2.0 Token Introspection (RFC 7662)."""
776 
777import logging
778from typing import Any
779 
780from mcp.server.auth.provider import AccessToken, TokenVerifier
781from mcp.shared.auth_utils import check_resource_allowed, resource_url_from_server_url
782 
783logger = logging.getLogger(__name__)
784 
785 
786class IntrospectionTokenVerifier(TokenVerifier):
787 """Token verifier that uses OAuth 2.0 Token Introspection (RFC 7662).
788 """
789 
790 def __init__(
791 self,
792 introspection_endpoint: str,
793 server_url: str,
794 client_id: str,
795 client_secret: str,
796 ):
797 self.introspection_endpoint = introspection_endpoint
798 self.server_url = server_url
799 self.client_id = client_id
800 self.client_secret = client_secret
801 self.resource_url = resource_url_from_server_url(server_url)
802 
803 async def verify_token(self, token: str) -> AccessToken | None:
804 """Verify token via introspection endpoint."""
805 import httpx
806 
807 if not self.introspection_endpoint.startswith(("https://", "http://localhost", "http://127.0.0.1")):
808 return None
809 
810 timeout = httpx.Timeout(10.0, connect=5.0)
811 limits = httpx.Limits(max_connections=10, max_keepalive_connections=5)
812 
813 async with httpx.AsyncClient(
814 timeout=timeout,
815 limits=limits,
816 verify=True,
817 ) as client:
818 try:
819 form_data = {
820 "token": token,
821 "client_id": self.client_id,
822 "client_secret": self.client_secret,
823 }
824 headers = {"Content-Type": "application/x-www-form-urlencoded"}
825 
826 response = await client.post(
827 self.introspection_endpoint,
828 data=form_data,
829 headers=headers,
830 )
831 
832 if response.status_code != 200:
833 return None
834 
835 data = response.json()
836 if not data.get("active", False):
837 return None
838 
839 if not self._validate_resource(data):
840 return None
841 
842 return AccessToken(
843 token=token,
844 client_id=data.get("client_id", "unknown"),
845 scopes=data.get("scope", "").split() if data.get("scope") else [],
846 expires_at=data.get("exp"),
847 resource=data.get("aud"), # Include resource in token
848 )
849 
850 except Exception as e:
851 return None
852 
853 def _validate_resource(self, token_data: dict[str, Any]) -> bool:
854 """Validate token was issued for this resource server.
855 
856 Rules:
857 - Reject if 'aud' missing.
858 - Accept if any audience entry matches the derived resource URL.
859 - Supports string or list forms per JWT spec.
860 """
861 if not self.server_url or not self.resource_url:
862 return False
863 
864 aud: list[str] | str | None = token_data.get("aud")
865 if isinstance(aud, list):
866 return any(self._is_valid_resource(a) for a in aud)
867 if isinstance(aud, str):
868 return self._is_valid_resource(aud)
869 return False
870 
871 def _is_valid_resource(self, resource: str) -> bool:
872 """Check if the given resource matches our server."""
873 return check_resource_allowed(self.resource_url, resource)
874```
875 
876For more details, see the [Python SDK documentation](https://github.com/modelcontextprotocol/python-sdk).
877 
878**C#**
879 
880You can see the complete C# project in the [sample repository](https://github.com/localden/min-cs-mcp-auth).
881 
882To set up authorization in your MCP server using the MCP C# SDK, you can lean on the standard ASP.NET Core builder pattern. Instead of using the introspection endpoint provided by Keycloak, we will use built-in ASP.NET Core capabilities for token validation.
883 
884```csharp theme={null}
885using Microsoft.AspNetCore.Authentication.JwtBearer;
886using Microsoft.IdentityModel.Tokens;
887using ModelContextProtocol.AspNetCore.Authentication;
888using ProtectedMcpServer.Tools;
889using System.Security.Claims;
890 
891var builder = WebApplication.CreateBuilder(args);
892 
893var serverUrl = "http://localhost:3000/";
894var authorizationServerUrl = "http://localhost:8080/realms/master/";
895 
896builder.Services.AddAuthentication(options =>
897{
898 options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;
899 options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
900})
901.AddJwtBearer(options =>
902{
903 options.Authority = authorizationServerUrl;
904 var normalizedServerAudience = serverUrl.TrimEnd('/');
905 options.TokenValidationParameters = new TokenValidationParameters
906 {
907 ValidIssuer = authorizationServerUrl,
908 ValidAudiences = new[] { normalizedServerAudience, serverUrl },
909 AudienceValidator = (audiences, securityToken, validationParameters) =>
910 {
911 if (audiences == null) return false;
912 foreach (var aud in audiences)
913 {
914 if (string.Equals(aud.TrimEnd('/'), normalizedServerAudience, StringComparison.OrdinalIgnoreCase))
915 {
916 return true;
917 }
918 }
919 return false;
405920 }
406 
407 if (!response.ok) {
408 const txt = await response.text();
409 console.error("[auth] introspection non-OK", { status: response.status });
410 
411 try {
412 const obj = JSON.parse(txt);
413 console.log(JSON.stringify(obj, null, 2));
414 } catch {
415 console.error(txt);
416 }
417 throw new Error(`Invalid or expired token: ${txt}`);
418 }
419 
420 let data: any;
421 try {
422 data = await response.json();
423 } catch (e) {
424 const txt = await response.text();
425 console.error("[auth] failed to parse introspection JSON", {
426 error: String(e),
427 body: txt,
428 });
429 throw e;
430 }
431 
432 if (data.active === false) {
433 throw new Error("Inactive token");
434 }
435 
436 if (!data.aud) {
437 throw new Error("Resource indicator (aud) missing");
438 }
439 
440 const audiences: string[] = Array.isArray(data.aud) ? data.aud : [data.aud];
441 const allowed = audiences.some((a) =>
442 checkResourceAllowed({
443 requestedResource: a,
444 configuredResource: mcpServerUrl,
445 }),
446 );
447 if (!allowed) {
448 throw new Error(
449 `None of the provided audiences are allowed. Expected ${mcpServerUrl}, got: ${audiences.join(", ")}`,
450 );
451 }
452 
453 return {
454 token,
455 clientId: data.client_id,
456 scopes: data.scope ? data.scope.split(" ") : [],
457 expiresAt: data.exp,
458 };
459 },
460921 };
461 app.use(
462 mcpAuthMetadataRouter({
463 oauthMetadata,
464 resourceServerUrl: mcpServerUrl,
465 scopesSupported: ["mcp:tools"],
466 resourceName: "MCP Demo Server",
467 }),
468 );
469 
470 const authMiddleware = requireBearerAuth({
471 verifier: tokenVerifier,
472 requiredScopes: [],
473 resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl),
474 });
475 
476 const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {};
477 
478 function createMcpServer() {
479 const server = new McpServer({
480 name: "example-server",
481 version: "1.0.0",
482 });
483 
484 server.registerTool(
485 "add",
922 
923 options.RequireHttpsMetadata = false; // Set to true in production
924 
925 options.Events = new JwtBearerEvents
926 {
927 OnTokenValidated = context =>
486928 {
487 title: "Addition Tool",
488 description: "Add two numbers together",
489 inputSchema: {
490 a: z.number().describe("First number to add"),
491 b: z.number().describe("Second number to add"),
492 },
929 var name = context.Principal?.Identity?.Name ?? "unknown";
930 var email = context.Principal?.FindFirstValue("preferred_username") ?? "unknown";
931 Console.WriteLine($"Token validated for: {name} ({email})");
932 return Task.CompletedTask;
493933 },
494 async ({ a, b }) => ({
495 content: [{ type: "text", text: `${a} + ${b} = ${a + b}` }],
496 }),
497 );
498 
499 server.registerTool(
500 "multiply",
934 OnAuthenticationFailed = context =>
501935 {
502 title: "Multiplication Tool",
503 description: "Multiply two numbers together",
504 inputSchema: {
505 x: z.number().describe("First number to multiply"),
506 y: z.number().describe("Second number to multiply"),
507 },
936 Console.WriteLine($"Authentication failed: {context.Exception.Message}");
937 return Task.CompletedTask;
508938 },
509 async ({ x, y }) => ({
510 content: [{ type: "text", text: `${x} × ${y} = ${x * y}` }],
511 }),
512 );
513 
514 return server;
515 }
516 
517 const mcpPostHandler = async (req: express.Request, res: express.Response) => {
518 const sessionId = req.headers["mcp-session-id"] as string | undefined;
519 let transport: StreamableHTTPServerTransport;
520 
521 if (sessionId && transports[sessionId]) {
522 transport = transports[sessionId];
523 } else if (!sessionId && isInitializeRequest(req.body)) {
524 transport = new StreamableHTTPServerTransport({
525 sessionIdGenerator: () => randomUUID(),
526 onsessioninitialized: (sessionId) => {
527 transports[sessionId] = transport;
528 },
529 });
530 
531 transport.onclose = () => {
532 if (transport.sessionId) {
533 delete transports[transport.sessionId];
534 }
535 };
536 
537 const server = createMcpServer();
538 await server.connect(transport);
539 } else {
540 res.status(400).json({
541 jsonrpc: "2.0",
542 error: {
543 code: -32000,
544 message: "Bad Request: No valid session ID provided",
545 },
546 id: null,
547 });
548 return;
549 }
550 
551 await transport.handleRequest(req, res, req.body);
552939 };
553 
554 const handleSessionRequest = async (
555 req: express.Request,
556 res: express.Response,
557 ) => {
558 const sessionId = req.headers["mcp-session-id"] as string | undefined;
559 if (!sessionId || !transports[sessionId]) {
560 res.status(400).send("Invalid or missing session ID");
561 return;
562 }
563 
564 const transport = transports[sessionId];
565 await transport.handleRequest(req, res);
940})
941.AddMcp(options =>
942{
943 options.ResourceMetadata = new()
944 {
945 Resource = new Uri(serverUrl),
946 ResourceDocumentation = new Uri("https://docs.example.com/api/math"),
947 AuthorizationServers = { new Uri(authorizationServerUrl) },
948 ScopesSupported = ["mcp:tools"]
566949 };
567 
568 app.post("/", authMiddleware, mcpPostHandler);
569 app.get("/", authMiddleware, handleSessionRequest);
570 app.delete("/", authMiddleware, handleSessionRequest);
571 
572 app.listen(CONFIG.port, CONFIG.host, () => {
573 console.log(`🚀 MCP Server running on ${mcpServerUrl.origin}`);
574 console.log(`📡 MCP endpoint available at ${mcpServerUrl.origin}`);
575 console.log(
576 `🔐 OAuth metadata available at ${getOAuthProtectedResourceMetadataUrl(mcpServerUrl)}`,
577 );
578 });
579 ```
580 
581 When you run the server, you can add it to your MCP client, such as Visual Studio Code, by providing the MCP server endpoint.
582 
583 For more details about implementing MCP servers in TypeScript, refer to the [TypeScript SDK documentation](https://github.com/modelcontextprotocol/typescript-sdk).
584 </Tab>
585 
586 <Tab title="Python">
587 You can see the complete Python project in the [sample repository](https://github.com/modelcontextprotocol/python-sdk/tree/main/examples/servers/simple-auth).
588 
589 To simplify our authorization interaction, in Python scenarios we rely on [FastMCP](https://gofastmcp.com/getting-started/welcome). Many of the conventions around authorization, like the endpoints and token validation logic, are consistent across languages, but some offer simpler ways of integrating them in production scenarios.
590 
591 Prior to writing the actual server, we need to set up our configuration in `config.py` - the contents are entirely based on your local server setup:
592 
593 ```python theme={null}
594 """Configuration settings for the MCP auth server."""
595 
596 import os
597 from typing import Optional
598 
599 
600 class Config:
601 """Configuration class that loads from environment variables with sensible defaults."""
602 
603 # Server settings
604 HOST: str = os.getenv("HOST", "localhost")
605 PORT: int = int(os.getenv("PORT", "3000"))
606 
607 # Auth server settings
608 AUTH_HOST: str = os.getenv("AUTH_HOST", "localhost")
609 AUTH_PORT: int = int(os.getenv("AUTH_PORT", "8080"))
610 AUTH_REALM: str = os.getenv("AUTH_REALM", "master")
611 
612 # OAuth client settings
613 OAUTH_CLIENT_ID: str = os.getenv("OAUTH_CLIENT_ID", "mcp-server")
614 OAUTH_CLIENT_SECRET: str = os.getenv("OAUTH_CLIENT_SECRET", "UO3rmozkFFkXr0QxPTkzZ0LMXDidIikB")
615 
616 # Server settings
617 MCP_SCOPE: str = os.getenv("MCP_SCOPE", "mcp:tools")
618 OAUTH_STRICT: bool = os.getenv("OAUTH_STRICT", "false").lower() in ("true", "1", "yes")
619 TRANSPORT: str = os.getenv("TRANSPORT", "streamable-http")
620 
621 @property
622 def server_url(self) -> str:
623 """Build the server URL."""
624 return f"http://{self.HOST}:{self.PORT}"
625 
626 @property
627 def auth_base_url(self) -> str:
628 """Build the auth server base URL."""
629 return f"http://{self.AUTH_HOST}:{self.AUTH_PORT}/realms/{self.AUTH_REALM}/"
630 
631 def validate(self) -> None:
632 """Validate configuration."""
633 if self.TRANSPORT not in ["sse", "streamable-http"]:
634 raise ValueError(f"Invalid transport: {self.TRANSPORT}. Must be 'sse' or 'streamable-http'")
635 
636 
637 # Global configuration instance
638 config = Config()
639 
640 ```
641 
642 The server implementation is as follows:
643 
644 ```python theme={null}
645 import datetime
646 import logging
647 from typing import Any
648 
649 from pydantic import AnyHttpUrl
650 
651 from mcp.server.auth.settings import AuthSettings
652 from mcp.server.fastmcp.server import FastMCP
653 
654 from .config import config
655 from .token_verifier import IntrospectionTokenVerifier
656 
657 logger = logging.getLogger(__name__)
658 
659 
660 def create_oauth_urls() -> dict[str, str]:
661 """Create OAuth URLs based on configuration (Keycloak-style)."""
662 from urllib.parse import urljoin
663 
664 auth_base_url = config.auth_base_url
665 
666 return {
667 "issuer": auth_base_url,
668 "introspection_endpoint": urljoin(auth_base_url, "protocol/openid-connect/token/introspect"),
669 "authorization_endpoint": urljoin(auth_base_url, "protocol/openid-connect/auth"),
670 "token_endpoint": urljoin(auth_base_url, "protocol/openid-connect/token"),
671 }
672 
673 
674 def create_server() -> FastMCP:
675 """Create and configure the FastMCP server."""
676 
677 config.validate()
678 
679 oauth_urls = create_oauth_urls()
680 
681 token_verifier = IntrospectionTokenVerifier(
682 introspection_endpoint=oauth_urls["introspection_endpoint"],
683 server_url=config.server_url,
684 client_id=config.OAUTH_CLIENT_ID,
685 client_secret=config.OAUTH_CLIENT_SECRET,
686 )
687 
688 app = FastMCP(
689 name="MCP Resource Server",
690 instructions="Resource Server that validates tokens via Authorization Server introspection",
691 host=config.HOST,
692 port=config.PORT,
693 debug=True,
694 streamable_http_path="/",
695 token_verifier=token_verifier,
696 auth=AuthSettings(
697 issuer_url=AnyHttpUrl(oauth_urls["issuer"]),
698 required_scopes=[config.MCP_SCOPE],
699 resource_server_url=AnyHttpUrl(config.server_url),
700 ),
701 )
702 
703 @app.tool()
704 async def add_numbers(a: float, b: float) -> dict[str, Any]:
705 """
706 Add two numbers together.
707 This tool demonstrates basic arithmetic operations with OAuth authentication.
708 
709 Args:
710 a: The first number to add
711 b: The second number to add
712 """
713 result = a + b
714 return {
715 "operation": "addition",
716 "operand_a": a,
717 "operand_b": b,
718 "result": result,
719 "timestamp": datetime.datetime.now().isoformat()
720 }
721 
722 @app.tool()
723 async def multiply_numbers(x: float, y: float) -> dict[str, Any]:
724 """
725 Multiply two numbers together.
726 This tool demonstrates basic arithmetic operations with OAuth authentication.
727 
728 Args:
729 x: The first number to multiply
730 y: The second number to multiply
731 """
732 result = x * y
733 return {
734 "operation": "multiplication",
735 "operand_x": x,
736 "operand_y": y,
737 "result": result,
738 "timestamp": datetime.datetime.now().isoformat()
739 }
740 
741 return app
742 
743 
744 def main() -> int:
745 """
746 Run the MCP Resource Server.
747 
748 This server:
749 - Provides RFC 9728 Protected Resource Metadata
750 - Validates tokens via Authorization Server introspection
751 - Serves MCP tools requiring authentication
752 
753 Configuration is loaded from config.py and environment variables.
754 """
755 logging.basicConfig(level=logging.INFO)
756 
757 try:
758 config.validate()
759 oauth_urls = create_oauth_urls()
760 
761 except ValueError as e:
762 logger.error("Configuration error: %s", e)
763 return 1
764 
765 try:
766 mcp_server = create_server()
767 
768 logger.info("Starting MCP Server on %s:%s", config.HOST, config.PORT)
769 logger.info("Authorization Server: %s", oauth_urls["issuer"])
770 logger.info("Transport: %s", config.TRANSPORT)
771 
772 mcp_server.run(transport=config.TRANSPORT)
773 return 0
774 
775 except Exception:
776 logger.exception("Server error")
777 return 1
778 
779 
780 if __name__ == "__main__":
781 exit(main())
782 ```
783 
784 Lastly, the token verification logic is delegated entirely to `token_verifier.py`, ensuring that we can use the Keycloak introspection endpoint to verify the validity of any credential artifacts
785 
786 ```python theme={null}
787 """Token verifier implementation using OAuth 2.0 Token Introspection (RFC 7662)."""
788 
789 import logging
790 from typing import Any
791 
792 from mcp.server.auth.provider import AccessToken, TokenVerifier
793 from mcp.shared.auth_utils import check_resource_allowed, resource_url_from_server_url
794 
795 logger = logging.getLogger(__name__)
796 
797 
798 class IntrospectionTokenVerifier(TokenVerifier):
799 """Token verifier that uses OAuth 2.0 Token Introspection (RFC 7662).
800 """
801 
802 def __init__(
803 self,
804 introspection_endpoint: str,
805 server_url: str,
806 client_id: str,
807 client_secret: str,
808 ):
809 self.introspection_endpoint = introspection_endpoint
810 self.server_url = server_url
811 self.client_id = client_id
812 self.client_secret = client_secret
813 self.resource_url = resource_url_from_server_url(server_url)
814 
815 async def verify_token(self, token: str) -> AccessToken | None:
816 """Verify token via introspection endpoint."""
817 import httpx
818 
819 if not self.introspection_endpoint.startswith(("https://", "http://localhost", "http://127.0.0.1")):
820 return None
821 
822 timeout = httpx.Timeout(10.0, connect=5.0)
823 limits = httpx.Limits(max_connections=10, max_keepalive_connections=5)
824 
825 async with httpx.AsyncClient(
826 timeout=timeout,
827 limits=limits,
828 verify=True,
829 ) as client:
830 try:
831 form_data = {
832 "token": token,
833 "client_id": self.client_id,
834 "client_secret": self.client_secret,
835 }
836 headers = {"Content-Type": "application/x-www-form-urlencoded"}
837 
838 response = await client.post(
839 self.introspection_endpoint,
840 data=form_data,
841 headers=headers,
842 )
843 
844 if response.status_code != 200:
845 return None
846 
847 data = response.json()
848 if not data.get("active", False):
849 return None
850 
851 if not self._validate_resource(data):
852 return None
853 
854 return AccessToken(
855 token=token,
856 client_id=data.get("client_id", "unknown"),
857 scopes=data.get("scope", "").split() if data.get("scope") else [],
858 expires_at=data.get("exp"),
859 resource=data.get("aud"), # Include resource in token
860 )
861 
862 except Exception as e:
863 return None
864 
865 def _validate_resource(self, token_data: dict[str, Any]) -> bool:
866 """Validate token was issued for this resource server.
867 
868 Rules:
869 - Reject if 'aud' missing.
870 - Accept if any audience entry matches the derived resource URL.
871 - Supports string or list forms per JWT spec.
872 """
873 if not self.server_url or not self.resource_url:
874 return False
875 
876 aud: list[str] | str | None = token_data.get("aud")
877 if isinstance(aud, list):
878 return any(self._is_valid_resource(a) for a in aud)
879 if isinstance(aud, str):
880 return self._is_valid_resource(aud)
881 return False
882 
883 def _is_valid_resource(self, resource: str) -> bool:
884 """Check if the given resource matches our server."""
885 return check_resource_allowed(self.resource_url, resource)
886 ```
887 
888 For more details, see the [Python SDK documentation](https://github.com/modelcontextprotocol/python-sdk).
889 </Tab>
890 
891 <Tab title="C#">
892 You can see the complete C# project in the [sample repository](https://github.com/localden/min-cs-mcp-auth).
893 
894 To set up authorization in your MCP server using the MCP C# SDK, you can lean on the standard ASP.NET Core builder pattern. Instead of using the introspection endpoint provided by Keycloak, we will use built-in ASP.NET Core capabilities for token validation.
895 
896 ```csharp theme={null}
897 using Microsoft.AspNetCore.Authentication.JwtBearer;
898 using Microsoft.IdentityModel.Tokens;
899 using ModelContextProtocol.AspNetCore.Authentication;
900 using ProtectedMcpServer.Tools;
901 using System.Security.Claims;
902 
903 var builder = WebApplication.CreateBuilder(args);
904 
905 var serverUrl = "http://localhost:3000/";
906 var authorizationServerUrl = "http://localhost:8080/realms/master/";
907 
908 builder.Services.AddAuthentication(options =>
909 {
910 options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;
911 options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
912 })
913 .AddJwtBearer(options =>
914 {
915 options.Authority = authorizationServerUrl;
916 var normalizedServerAudience = serverUrl.TrimEnd('/');
917 options.TokenValidationParameters = new TokenValidationParameters
918 {
919 ValidIssuer = authorizationServerUrl,
920 ValidAudiences = new[] { normalizedServerAudience, serverUrl },
921 AudienceValidator = (audiences, securityToken, validationParameters) =>
922 {
923 if (audiences == null) return false;
924 foreach (var aud in audiences)
925 {
926 if (string.Equals(aud.TrimEnd('/'), normalizedServerAudience, StringComparison.OrdinalIgnoreCase))
927 {
928 return true;
929 }
930 }
931 return false;
932 }
933 };
934 
935 options.RequireHttpsMetadata = false; // Set to true in production
936 
937 options.Events = new JwtBearerEvents
938 {
939 OnTokenValidated = context =>
940 {
941 var name = context.Principal?.Identity?.Name ?? "unknown";
942 var email = context.Principal?.FindFirstValue("preferred_username") ?? "unknown";
943 Console.WriteLine($"Token validated for: {name} ({email})");
944 return Task.CompletedTask;
945 },
946 OnAuthenticationFailed = context =>
947 {
948 Console.WriteLine($"Authentication failed: {context.Exception.Message}");
949 return Task.CompletedTask;
950 },
951 };
952 })
953 .AddMcp(options =>
954 {
955 options.ResourceMetadata = new()
956 {
957 Resource = new Uri(serverUrl),
958 ResourceDocumentation = new Uri("https://docs.example.com/api/math"),
959 AuthorizationServers = { new Uri(authorizationServerUrl) },
960 ScopesSupported = ["mcp:tools"]
961 };
962 });
963 
964 builder.Services.AddAuthorization();
965 
966 builder.Services.AddHttpContextAccessor();
967 builder.Services.AddMcpServer()
968 .WithTools<MathTools>()
969 .WithHttpTransport();
970 
971 var app = builder.Build();
972 
973 app.UseAuthentication();
974 app.UseAuthorization();
975 
976 app.MapMcp().RequireAuthorization();
977 
978 Console.WriteLine($"Starting MCP server with authorization at {serverUrl}");
979 Console.WriteLine($"Using Keycloak server at {authorizationServerUrl}");
980 Console.WriteLine($"Protected Resource Metadata URL: {serverUrl}.well-known/oauth-protected-resource");
981 Console.WriteLine("Exposed Math tools: Add, Multiply");
982 Console.WriteLine("Press Ctrl+C to stop the server");
983 
984 app.Run(serverUrl);
985 ```
986 
987 For more details, see the [C# SDK documentation](https://github.com/modelcontextprotocol/csharp-sdk).
988 </Tab>
989</Tabs>
950});
951 
952builder.Services.AddAuthorization();
953 
954builder.Services.AddHttpContextAccessor();
955builder.Services.AddMcpServer()
956 .WithTools<MathTools>()
957 .WithHttpTransport();
958 
959var app = builder.Build();
960 
961app.UseAuthentication();
962app.UseAuthorization();
963 
964app.MapMcp().RequireAuthorization();
965 
966Console.WriteLine($"Starting MCP server with authorization at {serverUrl}");
967Console.WriteLine($"Using Keycloak server at {authorizationServerUrl}");
968Console.WriteLine($"Protected Resource Metadata URL: {serverUrl}.well-known/oauth-protected-resource");
969Console.WriteLine("Exposed Math tools: Add, Multiply");
970Console.WriteLine("Press Ctrl+C to stop the server");
971 
972app.Run(serverUrl);
973```
974 
975For more details, see the [C# SDK documentation](https://github.com/modelcontextprotocol/csharp-sdk).
990976 
991977## Testing the MCP Server
992978 
from line 989
1003989 
1004990On connection, you will be taken to the browser, where you will be prompted to consent to Visual Studio Code having access to the `mcp:tools` scope.
1005991 
1006<Frame>
1007 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-vscode.png?fit=max&auto=format&n=sAd4SGUO-cEUqgzn&q=85&s=d5183fb7c257993aed1b2246f0bbbb27" alt="Keycloak consent form for VS Code." width="1915" height="1536" data-path="images/tutorial-authorization/keycloak-vscode.png" />
1008</Frame>
992![Keycloak consent form for VS Code.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/keycloak-vscode.png?fit=max\&auto=format\&n=sAd4SGUO-cEUqgzn\&q=85\&s=d5183fb7c257993aed1b2246f0bbbb27)
1009993 
1010994After consenting, you will see the tools listed right above the server entry in `mcp.json`.
1011995 
1012<Frame>
1013 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/tools-vs-code.png?fit=max&auto=format&n=sAd4SGUO-cEUqgzn&q=85&s=f7c34d1bf115fe6934e01b4a5a91168b" alt="Tools listed in VS Code." width="496" height="160" data-path="images/tutorial-authorization/tools-vs-code.png" />
1014</Frame>
996![Tools listed in VS Code.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/tools-vs-code.png?fit=max\&auto=format\&n=sAd4SGUO-cEUqgzn\&q=85\&s=f7c34d1bf115fe6934e01b4a5a91168b)
1015997 
1016998You will be able to invoke individual tools with the help of the `#` sign in the chat view.
1017999 
1018<Frame>
1019 <img src="https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/tools-vs-code-invoke.png?fit=max&auto=format&n=sAd4SGUO-cEUqgzn&q=85&s=76cbef68e48821a3c5467bd20c7e89fe" alt="Invoking MCP tools in VS Code." width="1276" height="396" data-path="images/tutorial-authorization/tools-vs-code-invoke.png" />
1020</Frame>
1000![Invoking MCP tools in VS Code.](https://mintcdn.com/mcp/sAd4SGUO-cEUqgzn/images/tutorial-authorization/tools-vs-code-invoke.png?fit=max\&auto=format\&n=sAd4SGUO-cEUqgzn\&q=85\&s=76cbef68e48821a3c5467bd20c7e89fe)
10211001 
10221002## Common Pitfalls and How to Avoid Them
10231003 
10241004 

docs/2025-11-25/tutorials/security/security_best_practices Changed · +4 / -4 lines

from line 423
423423* Link-local: `169.254.0.0/16` (including cloud metadata endpoints)
424424* Private IPv6 ranges: `fc00::/7`, `fe80::/10`
425425 
426<Note>
427 Avoid implementing IP validation manually. Attackers exploit encoding tricks
428 (octal, hex, IPv4-mapped IPv6) that custom parsers often miss.
429</Note>
426> [!NOTE]
427>
428> Avoid implementing IP validation manually. Attackers exploit encoding tricks
429> (octal, hex, IPv4-mapped IPv6) that custom parsers often miss.
430430 
431431**Validate Redirect Targets**
432432 

docs/2026-07-28/develop/build-client Changed · +2436 / -2452 lines

## System Requirements ## Setting Up Your Environment ## Setting Up Your API Key ## Creating the Client ### Imports and Setup ### Server Connection Management ### Query Processing Logic ### Interactive Chat Interface ### Main Entry Point ## Key Components Explained ### 1. Client Initialization ### 2. Server Connection ### 3. Query Processing ### 4. Interactive Interface ### 5. Resource Management ## Common Customization Points ## Running the Client ## How It Works ## Best practices ## Troubleshooting ### Server Path Issues ### Response Timing ### Common Error Messages ## System Requirements ## Setting Up Your Environment ## Setting Up Your API Key ## Creating the Client ### Basic Client Structure ### Server Connection Management ### Query Processing Logic ### Interactive Chat Interface ### Main Entry Point ## Running the Client ## How It Works ## Best practices ## Troubleshooting ### Server Path Issues ### Response Timing ### Common Error Messages ## System Requirements ## Setting Up Your Environment ## How it Works ### MCP Client Configuration ### Chat Implementation ### Build and run ### Advanced Configuration ## System Requirements ## Setting up your environment ## Setting up your API key ## Creating the Client ### Basic Client Structure ### Server connection management ### Query processing logic ### Interactive chat ### Main entry point ## Running the client ## How it works ## Best practices ## Troubleshooting ### Server Path Issues ### Build Issues ### Response Timing ### Common Error Messages ## System Requirements ## Setting up your environment ## Setting up your API key ## Creating the Client ### Basic Client Structure ### Query processing logic ## Key Components Explained ### 1. Client Initialization ### 2. Server Connection ### 3. Query Processing ## Running the Client ## System Requirements ## Setting Up Your Environment ## Setting Up Your API Key ## Creating the Client ### Basic Client Structure ### Server Connection Management ### Query Processing Logic ### Interactive Chat Interface ### Main Entry Point ## Key Components Explained ### 1. Client Initialization ### 2. Server Connection ### 3. Query Processing ### 4. Interactive Interface ### 5. Resource Management ## Running the Client ## How It Works ## Best practices ## Troubleshooting ### Server Path Issues ### Response Timing ### Common Error Messages ## System Requirements ## Setting Up Your Environment ## Setting Up Your API Key ## Creating the Client ### Imports and Client Structure ### Client Initialization ### Server Connection Management ### Converting MCP Tools ### Sending Model Requests ### Query Processing Logic ### Interactive Chat Interface ### Cleanup ### Main Entry Point ### Verify the Complete File ## Running the Client ## How It Works ## Best Practices ## Troubleshooting ### Server Command Issues ### Environment File Issues ### Tool and Response Errors

The two sides of this change are more than 400 edits apart, too far apart to line up, so this is the differ's own diff of it and the words inside a line are not marked.

from line 6
66 
77Before you begin, it helps to have gone through our [Build an MCP Server](/docs/2026-07-28/develop/build-server) tutorial so you can understand how clients and servers communicate.
88 
9<Tabs>
10 <Tab title="Python">
11 [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-python)
12 
13 ## System Requirements
14 
15 Before starting, ensure your system meets these requirements:
16 
17 * Mac or Windows computer
18 * Latest Python version installed
19 * Latest version of `uv` installed
20 * You must use the Python MCP SDK 2.0.0 or higher
21 
22 ## Setting Up Your Environment
23 
24 First, create a new Python project with `uv`:
25 
26 <CodeGroup>
27 ```bash macOS/Linux theme={null}
28 # Create project directory
29 uv init mcp-client
30 cd mcp-client
31 
32 # Create virtual environment
33 uv venv
34 
35 # Activate virtual environment
36 source .venv/bin/activate
37 
38 # Install required packages
39 uv add mcp anthropic python-dotenv
40 
41 # Remove boilerplate files
42 rm main.py
43 
44 # Create our main file
45 touch client.py
46 ```
47 
48 ```powershell Windows theme={null}
49 # Create project directory
50 uv init mcp-client
51 cd mcp-client
52 
53 # Create virtual environment
54 uv venv
55 
56 # Activate virtual environment
57 .venv\Scripts\activate
58 
59 # Install required packages
60 uv add mcp anthropic python-dotenv
61 
62 # Remove boilerplate files
63 del main.py
64 
65 # Create our main file
66 new-item client.py
67 ```
68 </CodeGroup>
69 
70 ## Setting Up Your API Key
71 
72 You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
73 
74 Create a `.env` file to store it:
75 
76 ```bash theme={null}
77 echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env
78 ```
79 
80 Add `.env` to your `.gitignore`:
81 
82 ```bash theme={null}
83 echo ".env" >> .gitignore
84 ```
85 
86 <Warning>
87 Make sure you keep your `ANTHROPIC_API_KEY` secure!
88 </Warning>
89 
90 ## Creating the Client
91 
92 ### Imports and Setup
93 
94 First, let's set up our imports and the pieces the rest of the file shares:
95 
96 ```python theme={null}
97 import asyncio
98 import sys
99 
100 from mcp import Client, StdioServerParameters
101 from mcp.client.stdio import stdio_client
102 from mcp_types import TextContent
103 
104 from anthropic import Anthropic
105 from dotenv import load_dotenv
106 
107 load_dotenv() # load environment variables from .env
108 
109 MODEL = "claude-opus-5"
110 anthropic = Anthropic()
111 ```
112 
113 `Client` is the single object your program talks to the server through. Listing the tools, calling one, reading a resource: each of those is a method on it.
114 
115 ### Server Connection Management
116 
117 Next, we'll work out which process to launch for a given server script:
118 
119 ```python theme={null}
120 def server_params(server_script_path: str) -> StdioServerParameters:
121 """Describe the subprocess that runs an MCP server
122 
123 Args:
124 server_script_path: Path to the server script (.py or .js)
125 """
126 if server_script_path.endswith(".py"):
127 command = "python"
128 elif server_script_path.endswith(".js"):
129 command = "node"
130 else:
131 raise ValueError("Server script must be a .py or .js file")
132 
133 return StdioServerParameters(command=command, args=[server_script_path])
134 ```
135 
136 `StdioServerParameters` is configuration, not a connection. `stdio_client()` turns it into a stdio transport, and `Client` opens that transport when you enter its `async with` block. We'll do both in `main()`.
137 
138 ### Query Processing Logic
139 
140 Now let's add the core functionality for processing queries and handling tool calls:
141 
142 ```python theme={null}
143 async def process_query(client: Client, query: str) -> str:
144 """Process a query using Claude and available tools"""
145 messages = [
146 {
147 "role": "user",
148 "content": query
149 }
150 ]
151 
152 tool_list = await client.list_tools()
153 available_tools = [{
154 "name": tool.name,
155 "description": tool.description,
156 "input_schema": tool.input_schema
157 } for tool in tool_list.tools]
158 
159 # Initial Claude API call
9**Python**
10 
11[You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-python)
12 
13## System Requirements
14 
15Before starting, ensure your system meets these requirements:
16 
17* Mac or Windows computer
18* Latest Python version installed
19* Latest version of `uv` installed
20* You must use the Python MCP SDK 2.0.0 or higher
21 
22## Setting Up Your Environment
23 
24First, create a new Python project with `uv`:
25 
26```bash macOS/Linux theme={null}
27# Create project directory
28uv init mcp-client
29cd mcp-client
30 
31# Create virtual environment
32uv venv
33 
34# Activate virtual environment
35source .venv/bin/activate
36 
37# Install required packages
38uv add mcp anthropic python-dotenv
39 
40# Remove boilerplate files
41rm main.py
42 
43# Create our main file
44touch client.py
45```
46 
47```powershell Windows theme={null}
48# Create project directory
49uv init mcp-client
50cd mcp-client
51 
52# Create virtual environment
53uv venv
54 
55# Activate virtual environment
56.venv\Scripts\activate
57 
58# Install required packages
59uv add mcp anthropic python-dotenv
60 
61# Remove boilerplate files
62del main.py
63 
64# Create our main file
65new-item client.py
66```
67 
68## Setting Up Your API Key
69 
70You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
71 
72Create a `.env` file to store it:
73 
74```bash theme={null}
75echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env
76```
77 
78Add `.env` to your `.gitignore`:
79 
80```bash theme={null}
81echo ".env" >> .gitignore
82```
83 
84> [!WARNING]
85>
86> Make sure you keep your `ANTHROPIC_API_KEY` secure!
87 
88## Creating the Client
89 
90### Imports and Setup
91 
92First, let's set up our imports and the pieces the rest of the file shares:
93 
94```python theme={null}
95import asyncio
96import sys
97 
98from mcp import Client, StdioServerParameters
99from mcp.client.stdio import stdio_client
100from mcp_types import TextContent
101 
102from anthropic import Anthropic
103from dotenv import load_dotenv
104 
105load_dotenv() # load environment variables from .env
106 
107MODEL = "claude-opus-5"
108anthropic = Anthropic()
109```
110 
111`Client` is the single object your program talks to the server through. Listing the tools, calling one, reading a resource: each of those is a method on it.
112 
113### Server Connection Management
114 
115Next, we'll work out which process to launch for a given server script:
116 
117```python theme={null}
118def server_params(server_script_path: str) -> StdioServerParameters:
119 """Describe the subprocess that runs an MCP server
120 
121 Args:
122 server_script_path: Path to the server script (.py or .js)
123 """
124 if server_script_path.endswith(".py"):
125 command = "python"
126 elif server_script_path.endswith(".js"):
127 command = "node"
128 else:
129 raise ValueError("Server script must be a .py or .js file")
130 
131 return StdioServerParameters(command=command, args=[server_script_path])
132```
133 
134`StdioServerParameters` is configuration, not a connection. `stdio_client()` turns it into a stdio transport, and `Client` opens that transport when you enter its `async with` block. We'll do both in `main()`.
135 
136### Query Processing Logic
137 
138Now let's add the core functionality for processing queries and handling tool calls:
139 
140```python theme={null}
141async def process_query(client: Client, query: str) -> str:
142 """Process a query using Claude and available tools"""
143 messages = [
144 {
145 "role": "user",
146 "content": query
147 }
148 ]
149 
150 tool_list = await client.list_tools()
151 available_tools = [{
152 "name": tool.name,
153 "description": tool.description,
154 "input_schema": tool.input_schema
155 } for tool in tool_list.tools]
156 
157 # Initial Claude API call
158 response = anthropic.messages.create(
159 model=MODEL,
160 max_tokens=1000,
161 messages=messages,
162 tools=available_tools
163 )
164 
165 # Process response and handle tool calls
166 final_text = []
167 tool_results = []
168 
169 for content in response.content:
170 if content.type == 'text':
171 final_text.append(content.text)
172 elif content.type == 'tool_use':
173 tool_name = content.name
174 tool_args = content.input
175 
176 # Execute tool call
177 result = await client.call_tool(tool_name, tool_args)
178 final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")
179 
180 tool_results.append({
181 "type": "tool_result",
182 "tool_use_id": content.id,
183 "content": "\n".join(
184 block.text
185 for block in result.content
186 if isinstance(block, TextContent)
187 ),
188 "is_error": result.is_error
189 })
190 
191 if tool_results:
192 messages.append({"role": "assistant", "content": response.content})
193 messages.append({"role": "user", "content": tool_results})
194 
195 # Get next response from Claude
160196 response = anthropic.messages.create(
161197 model=MODEL,
162198 max_tokens=1000,
from line 200
164200 tools=available_tools
165201 )
166202 
167 # Process response and handle tool calls
168 final_text = []
169 tool_results = []
170 
171203 for content in response.content:
172204 if content.type == 'text':
173205 final_text.append(content.text)
174 elif content.type == 'tool_use':
175 tool_name = content.name
176 tool_args = content.input
177 
178 # Execute tool call
179 result = await client.call_tool(tool_name, tool_args)
180 final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")
181 
182 tool_results.append({
183 "type": "tool_result",
184 "tool_use_id": content.id,
185 "content": "\n".join(
186 block.text
187 for block in result.content
188 if isinstance(block, TextContent)
189 ),
190 "is_error": result.is_error
191 })
192 
193 if tool_results:
194 messages.append({"role": "assistant", "content": response.content})
195 messages.append({"role": "user", "content": tool_results})
196 
197 # Get next response from Claude
198 response = anthropic.messages.create(
199 model=MODEL,
200 max_tokens=1000,
201 messages=messages,
202 tools=available_tools
203 )
204 
205 for content in response.content:
206 if content.type == 'text':
207 final_text.append(content.text)
208 
209 return "\n".join(final_text)
210 ```
211 
212 `call_tool` returns a `CallToolResult`. Its `content` is a list of blocks, which is why we narrow to `TextContent` before reading `.text`. A tool that raises does not raise here: it answers with `is_error` set, and passing that flag on lets Claude read the message and try something else.
213 
214 ### Interactive Chat Interface
215 
216 Now we'll add the chat loop:
217 
218 ```python theme={null}
219 async def chat_loop(client: Client) -> None:
220 """Run an interactive chat loop"""
221 print("\nMCP Client Started!")
222 print("Type your queries or 'quit' to exit.")
223 
224 while True:
225 try:
226 query = (await asyncio.to_thread(input, "\nQuery: ")).strip()
227 except EOFError:
228 break
229 
230 if query.lower() == 'quit':
231 break
232 
233 try:
234 response = await process_query(client, query)
235 print("\n" + response)
236 except Exception as e:
237 print(f"\nError: {e}")
238 ```
239 
240 `input()` blocks, so it runs on a worker thread. That keeps the event loop free to service the connection while you type.
241 
242 ### Main Entry Point
243 
244 Finally, we'll add the main execution logic:
245 
246 ```python theme={null}
247 async def main() -> None:
248 if len(sys.argv) < 2:
249 print("Usage: python client.py <path_to_server_script>")
250 sys.exit(1)
251 
252 async with Client(stdio_client(server_params(sys.argv[1]))) as client:
253 tool_list = await client.list_tools()
254 tool_names = [tool.name for tool in tool_list.tools]
255 print("\nConnected to server with tools:", tool_names)
256 
257 await chat_loop(client)
258 
259 
260 if __name__ == "__main__":
261 asyncio.run(main())
262 ```
263 
264 That `async with` is the entire connection lifecycle. Entering it launches the server and agrees a protocol version with it; leaving it disconnects and shuts the subprocess down. There is nothing to close by hand.
265 
266 You can find the complete `client.py` file [here](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-python/client.py).
267 
268 ## Key Components Explained
269 
270 ### 1. Client Initialization
271 
272 * A single `Client` carries the connection, and `async with` is its whole lifecycle
273 * There is no connect/close pair to call and nothing to clean up afterwards
274 * Configures the Anthropic client for Claude interactions
275 
276 ### 2. Server Connection
277 
278 * Supports both Python and Node.js servers
279 * Validates server script type
280 * Launches the server as a subprocess and speaks stdio to it
281 * Lists the available tools once the connection is open
282 
283 ### 3. Query Processing
284 
285 * Maintains conversation context
286 * Handles Claude's responses and tool calls
287 * Manages the message flow between Claude and tools
288 * Combines results into a coherent response
289 
290 ### 4. Interactive Interface
291 
292 * Provides a simple command-line interface
293 * Handles user input and displays responses
294 * Includes basic error handling
295 * Allows graceful exit
296 
297 ### 5. Resource Management
298 
299 * Leaving the `async with` block disconnects and shuts the server subprocess down
300 * A failing query is reported without ending the session
301 * Typing `quit`, or closing standard input, exits cleanly
302 
303 ## Common Customization Points
304 
305 1. **Tool Handling**
306 * Modify `process_query()` to handle specific tool types
307 * Add custom error handling for tool calls
308 * Implement tool-specific response formatting
309 
310 2. **Response Processing**
311 * Customize how tool results are formatted
312 * Add response filtering or transformation
313 * Implement custom logging
314 
315 3. **User Interface**
316 * Add a GUI or web interface
317 * Implement rich console output
318 * Add command history or auto-completion
319 
320 ## Running the Client
321 
322 To run your client with any MCP server:
323 
324 ```bash theme={null}
325 uv run client.py path/to/server.py # python server
326 uv run client.py path/to/build/index.js # node server
327 ```
328 
329 <Note>
330 If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python), your command might look something like this: `python client.py .../quickstart-resources/weather-server-python/weather.py`
331 </Note>
332 
333 The client will:
334 
335 1. Connect to the specified server
336 2. List available tools
337 3. Start an interactive chat session where you can:
338 * Enter queries
339 * See tool executions
340 * Get responses from Claude
341 
342 Here's an example of what it should look like if connected to the weather server from the server quickstart:
343 
344 <Frame>
345 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/client-claude-cli-python.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=686d6e0ae7c54f807827db111eaed7d4" width="1932" height="1739" data-path="images/client-claude-cli-python.png" />
346 </Frame>
347 
348 ## How It Works
349 
350 When you submit a query:
351 
352 1. The client gets the list of available tools from the server
353 2. Your query is sent to Claude along with tool descriptions
354 3. Claude decides which tools (if any) to use
355 4. The client executes any requested tool calls through the server
356 5. Results are sent back to Claude
357 6. Claude provides a natural language response
358 7. The response is displayed to you
359 
360 ## Best practices
361 
362 1. **Error Handling**
363 * Check `result.is_error` rather than expecting a failing tool to raise
364 * Provide meaningful error messages
365 * Gracefully handle connection issues
366 
367 2. **Resource Management**
368 * Let the `async with` block own the connection
369 * Keep it open for as long as you need the server
370 * Handle server disconnections
371 
372 3. **Security**
373 * Store API keys securely in `.env`
374 * Validate server responses
375 * Be cautious with tool permissions
376 
377 4. **Tool Names**
378 * Tool names can be validated according to the format specified [here](/specification/2026-07-28/server/tools#tool-names)
379 * If a tool name conforms to the specified format, it should not fail validation by an MCP client
380 
381 ## Troubleshooting
382 
383 ### Server Path Issues
384 
385 * Double-check the path to your server script is correct
386 * Use the absolute path if the relative path isn't working
387 * For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
388 * Verify the server file has the correct extension (.py for Python or .js for Node.js)
389 
390 Example of correct path usage:
391 
392 ```bash theme={null}
393 # Relative path
394 uv run client.py ./server/weather.py
395 
396 # Absolute path
397 uv run client.py /Users/username/projects/mcp-server/weather.py
398 
399 # Windows path (either format works)
400 uv run client.py C:/projects/mcp-server/weather.py
401 uv run client.py C:\\projects\\mcp-server\\weather.py
402 ```
403 
404 ### Response Timing
405 
406 * The first response might take up to 30 seconds to return
407 * This is normal and happens while:
408 * The server initializes
409 * Claude processes the query
410 * Tools are being executed
411 * Subsequent responses are typically faster
412 * Don't interrupt the process during this initial waiting period
413 
414 ### Common Error Messages
415 
416 If you see:
417 
418 * `FileNotFoundError`: Check your server path
419 * `Connection refused`: Ensure the server is running and the path is correct
420 * `Tool execution failed`: Verify the tool's required environment variables are set
421 * `Timeout error`: Consider raising `read_timeout_seconds` on the `Client`
422 </Tab>
423 
424 <Tab title="TypeScript">
425 [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-typescript)
426 
427 ## System Requirements
428 
429 Before starting, ensure your system meets these requirements:
430 
431 * Mac or Windows computer
432 * Node.js 20 or higher installed
433 * Latest version of `npm` installed
434 * Anthropic API key (Claude)
435 
436 ## Setting Up Your Environment
437 
438 First, let's create and set up our project:
439 
440 <CodeGroup>
441 ```bash macOS/Linux theme={null}
442 # Create project directory
443 mkdir mcp-client-typescript
444 cd mcp-client-typescript
445 
446 # Initialize npm project
447 npm init -y
448 
449 # Install dependencies
450 npm install @anthropic-ai/sdk @modelcontextprotocol/client dotenv
451 
452 # Install dev dependencies
453 npm install -D @types/node typescript
454 
455 # Create source file
456 touch index.ts
457 ```
458 
459 ```powershell Windows theme={null}
460 # Create project directory
461 md mcp-client-typescript
462 cd mcp-client-typescript
463 
464 # Initialize npm project
465 npm init -y
466 
467 # Install dependencies
468 npm install @anthropic-ai/sdk @modelcontextprotocol/client dotenv
469 
470 # Install dev dependencies
471 npm install -D @types/node typescript
472 
473 # Create source file
474 new-item index.ts
475 ```
476 </CodeGroup>
477 
478 Update your `package.json` to set `type: "module"` and a build script:
479 
480 ```json package.json theme={null}
206 
207 return "\n".join(final_text)
208```
209 
210`call_tool` returns a `CallToolResult`. Its `content` is a list of blocks, which is why we narrow to `TextContent` before reading `.text`. A tool that raises does not raise here: it answers with `is_error` set, and passing that flag on lets Claude read the message and try something else.
211 
212### Interactive Chat Interface
213 
214Now we'll add the chat loop:
215 
216```python theme={null}
217async def chat_loop(client: Client) -> None:
218 """Run an interactive chat loop"""
219 print("\nMCP Client Started!")
220 print("Type your queries or 'quit' to exit.")
221 
222 while True:
223 try:
224 query = (await asyncio.to_thread(input, "\nQuery: ")).strip()
225 except EOFError:
226 break
227 
228 if query.lower() == 'quit':
229 break
230 
231 try:
232 response = await process_query(client, query)
233 print("\n" + response)
234 except Exception as e:
235 print(f"\nError: {e}")
236```
237 
238`input()` blocks, so it runs on a worker thread. That keeps the event loop free to service the connection while you type.
239 
240### Main Entry Point
241 
242Finally, we'll add the main execution logic:
243 
244```python theme={null}
245async def main() -> None:
246 if len(sys.argv) < 2:
247 print("Usage: python client.py <path_to_server_script>")
248 sys.exit(1)
249 
250 async with Client(stdio_client(server_params(sys.argv[1]))) as client:
251 tool_list = await client.list_tools()
252 tool_names = [tool.name for tool in tool_list.tools]
253 print("\nConnected to server with tools:", tool_names)
254 
255 await chat_loop(client)
256 
257 
258if __name__ == "__main__":
259 asyncio.run(main())
260```
261 
262That `async with` is the entire connection lifecycle. Entering it launches the server and agrees a protocol version with it; leaving it disconnects and shuts the subprocess down. There is nothing to close by hand.
263 
264You can find the complete `client.py` file [here](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-python/client.py).
265 
266## Key Components Explained
267 
268### 1. Client Initialization
269 
270* A single `Client` carries the connection, and `async with` is its whole lifecycle
271* There is no connect/close pair to call and nothing to clean up afterwards
272* Configures the Anthropic client for Claude interactions
273 
274### 2. Server Connection
275 
276* Supports both Python and Node.js servers
277* Validates server script type
278* Launches the server as a subprocess and speaks stdio to it
279* Lists the available tools once the connection is open
280 
281### 3. Query Processing
282 
283* Maintains conversation context
284* Handles Claude's responses and tool calls
285* Manages the message flow between Claude and tools
286* Combines results into a coherent response
287 
288### 4. Interactive Interface
289 
290* Provides a simple command-line interface
291* Handles user input and displays responses
292* Includes basic error handling
293* Allows graceful exit
294 
295### 5. Resource Management
296 
297* Leaving the `async with` block disconnects and shuts the server subprocess down
298* A failing query is reported without ending the session
299* Typing `quit`, or closing standard input, exits cleanly
300 
301## Common Customization Points
302 
3031. **Tool Handling**
304 * Modify `process_query()` to handle specific tool types
305 * Add custom error handling for tool calls
306 * Implement tool-specific response formatting
307 
3082. **Response Processing**
309 * Customize how tool results are formatted
310 * Add response filtering or transformation
311 * Implement custom logging
312 
3133. **User Interface**
314 * Add a GUI or web interface
315 * Implement rich console output
316 * Add command history or auto-completion
317 
318## Running the Client
319 
320To run your client with any MCP server:
321 
322```bash theme={null}
323uv run client.py path/to/server.py # python server
324uv run client.py path/to/build/index.js # node server
325```
326 
327> [!NOTE]
328>
329> If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python), your command might look something like this: `python client.py .../quickstart-resources/weather-server-python/weather.py`
330 
331The client will:
332 
3331. Connect to the specified server
3342. List available tools
3353. Start an interactive chat session where you can:
336 * Enter queries
337 * See tool executions
338 * Get responses from Claude
339 
340Here's an example of what it should look like if connected to the weather server from the server quickstart:
341 
342![](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/client-claude-cli-python.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=686d6e0ae7c54f807827db111eaed7d4)
343 
344## How It Works
345 
346When you submit a query:
347 
3481. The client gets the list of available tools from the server
3492. Your query is sent to Claude along with tool descriptions
3503. Claude decides which tools (if any) to use
3514. The client executes any requested tool calls through the server
3525. Results are sent back to Claude
3536. Claude provides a natural language response
3547. The response is displayed to you
355 
356## Best practices
357 
3581. **Error Handling**
359 * Check `result.is_error` rather than expecting a failing tool to raise
360 * Provide meaningful error messages
361 * Gracefully handle connection issues
362 
3632. **Resource Management**
364 * Let the `async with` block own the connection
365 * Keep it open for as long as you need the server
366 * Handle server disconnections
367 
3683. **Security**
369 * Store API keys securely in `.env`
370 * Validate server responses
371 * Be cautious with tool permissions
372 
3734. **Tool Names**
374 * Tool names can be validated according to the format specified [here](/specification/2026-07-28/server/tools#tool-names)
375 * If a tool name conforms to the specified format, it should not fail validation by an MCP client
376 
377## Troubleshooting
378 
379### Server Path Issues
380 
381* Double-check the path to your server script is correct
382* Use the absolute path if the relative path isn't working
383* For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
384* Verify the server file has the correct extension (.py for Python or .js for Node.js)
385 
386Example of correct path usage:
387 
388```bash theme={null}
389# Relative path
390uv run client.py ./server/weather.py
391 
392# Absolute path
393uv run client.py /Users/username/projects/mcp-server/weather.py
394 
395# Windows path (either format works)
396uv run client.py C:/projects/mcp-server/weather.py
397uv run client.py C:\\projects\\mcp-server\\weather.py
398```
399 
400### Response Timing
401 
402* The first response might take up to 30 seconds to return
403* This is normal and happens while:
404 * The server initializes
405 * Claude processes the query
406 * Tools are being executed
407* Subsequent responses are typically faster
408* Don't interrupt the process during this initial waiting period
409 
410### Common Error Messages
411 
412If you see:
413 
414* `FileNotFoundError`: Check your server path
415* `Connection refused`: Ensure the server is running and the path is correct
416* `Tool execution failed`: Verify the tool's required environment variables are set
417* `Timeout error`: Consider raising `read_timeout_seconds` on the `Client`
418 
419**TypeScript**
420 
421[You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-typescript)
422 
423## System Requirements
424 
425Before starting, ensure your system meets these requirements:
426 
427* Mac or Windows computer
428* Node.js 20 or higher installed
429* Latest version of `npm` installed
430* Anthropic API key (Claude)
431 
432## Setting Up Your Environment
433 
434First, let's create and set up our project:
435 
436```bash macOS/Linux theme={null}
437# Create project directory
438mkdir mcp-client-typescript
439cd mcp-client-typescript
440 
441# Initialize npm project
442npm init -y
443 
444# Install dependencies
445npm install @anthropic-ai/sdk @modelcontextprotocol/client dotenv
446 
447# Install dev dependencies
448npm install -D @types/node typescript
449 
450# Create source file
451touch index.ts
452```
453 
454```powershell Windows theme={null}
455# Create project directory
456md mcp-client-typescript
457cd mcp-client-typescript
458 
459# Initialize npm project
460npm init -y
461 
462# Install dependencies
463npm install @anthropic-ai/sdk @modelcontextprotocol/client dotenv
464 
465# Install dev dependencies
466npm install -D @types/node typescript
467 
468# Create source file
469new-item index.ts
470```
471 
472Update your `package.json` to set `type: "module"` and a build script:
473 
474```json package.json theme={null}
475{
476 "type": "module",
477 "scripts": {
478 "build": "tsc && chmod 755 build/index.js"
479 }
480}
481```
482 
483Create a `tsconfig.json` in the root of your project:
484 
485```json tsconfig.json theme={null}
486{
487 "compilerOptions": {
488 "target": "ES2022",
489 "module": "Node16",
490 "moduleResolution": "Node16",
491 "types": ["node"],
492 "outDir": "./build",
493 "rootDir": "./",
494 "strict": true,
495 "esModuleInterop": true,
496 "skipLibCheck": true,
497 "forceConsistentCasingInFileNames": true
498 },
499 "include": ["index.ts"],
500 "exclude": ["node_modules"]
501}
502```
503 
504## Setting Up Your API Key
505 
506You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
507 
508Create a `.env` file to store it:
509 
510```bash theme={null}
511echo "ANTHROPIC_API_KEY=<your key here>" > .env
512```
513 
514Add `.env` to your `.gitignore`:
515 
516```bash theme={null}
517echo ".env" >> .gitignore
518```
519 
520> [!WARNING]
521>
522> Make sure you keep your `ANTHROPIC_API_KEY` secure!
523 
524## Creating the Client
525 
526### Basic Client Structure
527 
528First, let's set up our imports and create the basic client class in `index.ts`:
529 
530```typescript theme={null}
531import { Anthropic } from "@anthropic-ai/sdk";
532import {
533 MessageParam,
534 Tool,
535} from "@anthropic-ai/sdk/resources/messages/messages.mjs";
536import { Client } from "@modelcontextprotocol/client";
537import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
538import readline from "readline/promises";
539import dotenv from "dotenv";
540 
541dotenv.config();
542 
543const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
544if (!ANTHROPIC_API_KEY) {
545 throw new Error("ANTHROPIC_API_KEY is not set");
546}
547 
548class MCPClient {
549 private mcp: Client;
550 private anthropic: Anthropic;
551 private transport: StdioClientTransport | null = null;
552 private tools: Tool[] = [];
553 
554 constructor() {
555 this.anthropic = new Anthropic({
556 apiKey: ANTHROPIC_API_KEY,
557 });
558 this.mcp = new Client({ name: "mcp-client-cli", version: "1.0.0" });
559 }
560 // methods will go here
561}
562```
563 
564### Server Connection Management
565 
566Next, we'll implement the method to connect to an MCP server:
567 
568```typescript theme={null}
569async connectToServer(serverScriptPath: string) {
570 try {
571 const isJs = serverScriptPath.endsWith(".js");
572 const isPy = serverScriptPath.endsWith(".py");
573 if (!isJs && !isPy) {
574 throw new Error("Server script must be a .js or .py file");
575 }
576 const command = isPy
577 ? process.platform === "win32"
578 ? "python"
579 : "python3"
580 : process.execPath;
581 
582 this.transport = new StdioClientTransport({
583 command,
584 args: [serverScriptPath],
585 });
586 await this.mcp.connect(this.transport);
587 
588 const toolsResult = await this.mcp.listTools();
589 this.tools = toolsResult.tools.map((tool) => {
590 return {
591 name: tool.name,
592 description: tool.description,
593 input_schema: tool.inputSchema,
594 };
595 });
596 console.log(
597 "Connected to server with tools:",
598 this.tools.map(({ name }) => name)
599 );
600 } catch (e) {
601 console.log("Failed to connect to MCP server: ", e);
602 throw e;
603 }
604}
605```
606 
607### Query Processing Logic
608 
609Now let's add the core functionality for processing queries and handling tool calls:
610 
611```typescript theme={null}
612async processQuery(query: string) {
613 const messages: MessageParam[] = [
481614 {
482 "type": "module",
483 "scripts": {
484 "build": "tsc && chmod 755 build/index.js"
485 }
486 }
487 ```
488 
489 Create a `tsconfig.json` in the root of your project:
490 
491 ```json tsconfig.json theme={null}
492 {
493 "compilerOptions": {
494 "target": "ES2022",
495 "module": "Node16",
496 "moduleResolution": "Node16",
497 "types": ["node"],
498 "outDir": "./build",
499 "rootDir": "./",
500 "strict": true,
501 "esModuleInterop": true,
502 "skipLibCheck": true,
503 "forceConsistentCasingInFileNames": true
504 },
505 "include": ["index.ts"],
506 "exclude": ["node_modules"]
507 }
508 ```
509 
510 ## Setting Up Your API Key
511 
512 You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
513 
514 Create a `.env` file to store it:
515 
516 ```bash theme={null}
517 echo "ANTHROPIC_API_KEY=<your key here>" > .env
518 ```
519 
520 Add `.env` to your `.gitignore`:
521 
522 ```bash theme={null}
523 echo ".env" >> .gitignore
524 ```
525 
526 <Warning>
527 Make sure you keep your `ANTHROPIC_API_KEY` secure!
528 </Warning>
529 
530 ## Creating the Client
531 
532 ### Basic Client Structure
533 
534 First, let's set up our imports and create the basic client class in `index.ts`:
535 
536 ```typescript theme={null}
537 import { Anthropic } from "@anthropic-ai/sdk";
538 import {
539 MessageParam,
540 Tool,
541 } from "@anthropic-ai/sdk/resources/messages/messages.mjs";
542 import { Client } from "@modelcontextprotocol/client";
543 import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
544 import readline from "readline/promises";
545 import dotenv from "dotenv";
546 
547 dotenv.config();
548 
549 const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
550 if (!ANTHROPIC_API_KEY) {
551 throw new Error("ANTHROPIC_API_KEY is not set");
552 }
553 
554 class MCPClient {
555 private mcp: Client;
556 private anthropic: Anthropic;
557 private transport: StdioClientTransport | null = null;
558 private tools: Tool[] = [];
559 
560 constructor() {
561 this.anthropic = new Anthropic({
562 apiKey: ANTHROPIC_API_KEY,
563 });
564 this.mcp = new Client({ name: "mcp-client-cli", version: "1.0.0" });
565 }
566 // methods will go here
567 }
568 ```
569 
570 ### Server Connection Management
571 
572 Next, we'll implement the method to connect to an MCP server:
573 
574 ```typescript theme={null}
575 async connectToServer(serverScriptPath: string) {
576 try {
577 const isJs = serverScriptPath.endsWith(".js");
578 const isPy = serverScriptPath.endsWith(".py");
579 if (!isJs && !isPy) {
580 throw new Error("Server script must be a .js or .py file");
581 }
582 const command = isPy
583 ? process.platform === "win32"
584 ? "python"
585 : "python3"
586 : process.execPath;
587 
588 this.transport = new StdioClientTransport({
589 command,
590 args: [serverScriptPath],
591 });
592 await this.mcp.connect(this.transport);
593 
594 const toolsResult = await this.mcp.listTools();
595 this.tools = toolsResult.tools.map((tool) => {
596 return {
597 name: tool.name,
598 description: tool.description,
599 input_schema: tool.inputSchema,
600 };
601 });
602 console.log(
603 "Connected to server with tools:",
604 this.tools.map(({ name }) => name)
605 );
606 } catch (e) {
607 console.log("Failed to connect to MCP server: ", e);
608 throw e;
609 }
610 }
611 ```
612 
613 ### Query Processing Logic
614 
615 Now let's add the core functionality for processing queries and handling tool calls:
616 
617 ```typescript theme={null}
618 async processQuery(query: string) {
619 const messages: MessageParam[] = [
620 {
621 role: "user",
622 content: query,
623 },
624 ];
615 role: "user",
616 content: query,
617 },
618 ];
619 
620 const response = await this.anthropic.messages.create({
621 model: "claude-opus-5",
622 max_tokens: 1000,
623 messages,
624 tools: this.tools,
625 });
626 
627 const finalText = [];
628 
629 for (const content of response.content) {
630 if (content.type === "text") {
631 finalText.push(content.text);
632 } else if (content.type === "tool_use") {
633 const toolName = content.name;
634 const toolArgs = content.input as { [x: string]: unknown } | undefined;
635 
636 const result = await this.mcp.callTool({
637 name: toolName,
638 arguments: toolArgs,
639 });
640 finalText.push(
641 `[Calling tool ${toolName} with args ${JSON.stringify(toolArgs)}]`
642 );
643 
644 messages.push({
645 role: "user",
646 content: result.content
647 .filter((block) => block.type === "text")
648 .map((block) => block.text)
649 .join("\n"),
650 });
625651 
626652 const response = await this.anthropic.messages.create({
627653 model: "claude-opus-5",
628654 max_tokens: 1000,
629655 messages,
630 tools: this.tools,
631656 });
632657 
633 const finalText = [];
634 
635 for (const content of response.content) {
636 if (content.type === "text") {
637 finalText.push(content.text);
638 } else if (content.type === "tool_use") {
639 const toolName = content.name;
640 const toolArgs = content.input as { [x: string]: unknown } | undefined;
641 
642 const result = await this.mcp.callTool({
643 name: toolName,
644 arguments: toolArgs,
645 });
646 finalText.push(
647 `[Calling tool ${toolName} with args ${JSON.stringify(toolArgs)}]`
648 );
649 
650 messages.push({
651 role: "user",
652 content: result.content
653 .filter((block) => block.type === "text")
654 .map((block) => block.text)
655 .join("\n"),
656 });
657 
658 const response = await this.anthropic.messages.create({
659 model: "claude-opus-5",
660 max_tokens: 1000,
661 messages,
662 });
663 
664 finalText.push(
665 response.content[0].type === "text" ? response.content[0].text : ""
666 );
667 }
658 finalText.push(
659 response.content[0].type === "text" ? response.content[0].text : ""
660 );
661 }
662 }
663 
664 return finalText.join("\n");
665}
666```
667 
668### Interactive Chat Interface
669 
670Now we'll add the chat loop and cleanup functionality:
671 
672```typescript theme={null}
673async chatLoop() {
674 const rl = readline.createInterface({
675 input: process.stdin,
676 output: process.stdout,
677 });
678 
679 try {
680 console.log("\nMCP Client Started!");
681 console.log("Type your queries or 'quit' to exit.");
682 
683 while (true) {
684 const message = await rl.question("\nQuery: ");
685 if (message.toLowerCase() === "quit") {
686 break;
668687 }
669 
670 return finalText.join("\n");
688 const response = await this.processQuery(message);
689 console.log("\n" + response);
671690 }
672 ```
673 
674 ### Interactive Chat Interface
675 
676 Now we'll add the chat loop and cleanup functionality:
677 
678 ```typescript theme={null}
679 async chatLoop() {
680 const rl = readline.createInterface({
681 input: process.stdin,
682 output: process.stdout,
683 });
684 
685 try {
686 console.log("\nMCP Client Started!");
687 console.log("Type your queries or 'quit' to exit.");
688 
689 while (true) {
690 const message = await rl.question("\nQuery: ");
691 if (message.toLowerCase() === "quit") {
692 break;
693 }
694 const response = await this.processQuery(message);
695 console.log("\n" + response);
696 }
697 } finally {
698 rl.close();
691 } finally {
692 rl.close();
693 }
694}
695 
696async cleanup() {
697 await this.mcp.close();
698}
699```
700 
701### Main Entry Point
702 
703Finally, we'll add the main execution logic:
704 
705```typescript theme={null}
706async function main() {
707 if (process.argv.length < 3) {
708 console.log("Usage: node index.ts <path_to_server_script>");
709 return;
710 }
711 const mcpClient = new MCPClient();
712 try {
713 await mcpClient.connectToServer(process.argv[2]);
714 await mcpClient.chatLoop();
715 } catch (e) {
716 console.error("Error:", e);
717 await mcpClient.cleanup();
718 process.exit(1);
719 } finally {
720 await mcpClient.cleanup();
721 process.exit(0);
722 }
723}
724 
725main();
726```
727 
728## Running the Client
729 
730To run your client with any MCP server:
731 
732```bash theme={null}
733# Build TypeScript
734npm run build
735 
736# Run the client
737node build/index.js path/to/server.py # python server
738node build/index.js path/to/build/index.js # node server
739```
740 
741> [!NOTE]
742>
743> If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript), your command might look something like this: `node build/index.js .../quickstart-resources/weather-server-typescript/build/index.js`
744 
745**The client will:**
746 
7471. Connect to the specified server
7482. List available tools
7493. Start an interactive chat session where you can:
750 * Enter queries
751 * See tool executions
752 * Get responses from Claude
753 
754## How It Works
755 
756When you submit a query:
757 
7581. The client gets the list of available tools from the server
7592. Your query is sent to Claude along with tool descriptions
7603. Claude decides which tools (if any) to use
7614. The client executes any requested tool calls through the server
7625. Results are sent back to Claude
7636. Claude provides a natural language response
7647. The response is displayed to you
765 
766## Best practices
767 
7681. **Error Handling**
769 * Use TypeScript's type system for better error detection
770 * Wrap tool calls in try-catch blocks
771 * Provide meaningful error messages
772 * Gracefully handle connection issues
773 
7742. **Security**
775 * Store API keys securely in `.env`
776 * Validate server responses
777 * Be cautious with tool permissions
778 
779## Troubleshooting
780 
781### Server Path Issues
782 
783* Double-check the path to your server script is correct
784* Use the absolute path if the relative path isn't working
785* For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
786* Verify the server file has the correct extension (.js for Node.js or .py for Python)
787 
788Example of correct path usage:
789 
790```bash theme={null}
791# Relative path
792node build/index.js ./server/build/index.js
793 
794# Absolute path
795node build/index.js /Users/username/projects/mcp-server/build/index.js
796 
797# Windows path (either format works)
798node build/index.js C:/projects/mcp-server/build/index.js
799node build/index.js C:\\projects\\mcp-server\\build\\index.js
800```
801 
802### Response Timing
803 
804* The first response might take up to 30 seconds to return
805* This is normal and happens while:
806 * The server initializes
807 * Claude processes the query
808 * Tools are being executed
809* Subsequent responses are typically faster
810* Don't interrupt the process during this initial waiting period
811 
812### Common Error Messages
813 
814If you see:
815 
816* `Error: Cannot find module`: Check your build folder and ensure TypeScript compilation succeeded
817* `Connection refused`: Ensure the server is running and the path is correct
818* `Tool execution failed`: Verify the tool's required environment variables are set
819* `ANTHROPIC_API_KEY is not set`: Check your .env file and environment variables
820* `TypeError`: Ensure you're using the correct types for tool arguments
821* `BadRequestError`: Ensure you have enough credits to access the Anthropic API
822 
823**Java**
824 
825> [!NOTE]
826>
827> This is a quickstart demo based on Spring AI MCP auto-configuration and boot starters.
828> To learn how to create sync and async MCP Clients manually, consult the [Java SDK Client](https://java.sdk.modelcontextprotocol.io/) documentation.
829 
830This example demonstrates how to build an interactive chatbot that combines Spring AI's Model Context Protocol (MCP) with the [Brave Search MCP Server](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/brave-search). The application creates a conversational interface powered by Anthropic's Claude AI model that can perform internet searches through Brave Search, enabling natural language interactions with real-time web data.
831[You can find the complete code for this tutorial here.](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/web-search/brave-chatbot)
832 
833## System Requirements
834 
835Before starting, ensure your system meets these requirements:
836 
837* Java 17 or higher
838* Maven 3.6+
839* npx package manager
840* Anthropic API key (Claude)
841* Brave Search API key
842 
843## Setting Up Your Environment
844 
8451. Install npx (Node Package eXecute):
846 First, make sure to install [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)
847 and then run:
848 
849 ```bash theme={null}
850 npm install -g npx
851 ```
852 
8532. Clone the repository:
854 
855 ```bash theme={null}
856 git clone https://github.com/spring-projects/spring-ai-examples.git
857 cd model-context-protocol/web-search/brave-chatbot
858 ```
859 
8603. Set up your API keys:
861 
862 ```bash theme={null}
863 export ANTHROPIC_API_KEY='your-anthropic-api-key-here'
864 export BRAVE_API_KEY='your-brave-api-key-here'
865 ```
866 
8674. Build the application:
868 
869 ```bash theme={null}
870 ./mvnw clean install
871 ```
872 
8735. Run the application using Maven:
874 ```bash theme={null}
875 ./mvnw spring-boot:run
876 ```
877 
878> [!WARNING]
879>
880> Make sure you keep your `ANTHROPIC_API_KEY` and `BRAVE_API_KEY` keys secure!
881 
882## How it Works
883 
884The application integrates Spring AI with the Brave Search MCP server through several components:
885 
886### MCP Client Configuration
887 
8881. Required dependencies in pom.xml:
889 
890```xml theme={null}
891<dependency>
892 <groupId>org.springframework.ai</groupId>
893 <artifactId>spring-ai-starter-mcp-client</artifactId>
894</dependency>
895<dependency>
896 <groupId>org.springframework.ai</groupId>
897 <artifactId>spring-ai-starter-model-anthropic</artifactId>
898</dependency>
899```
900 
9012. Application properties (application.yml):
902 
903```yml theme={null}
904spring:
905 ai:
906 mcp:
907 client:
908 enabled: true
909 name: brave-search-client
910 version: 1.0.0
911 type: SYNC
912 request-timeout: 20s
913 stdio:
914 root-change-notification: true
915 servers-configuration: classpath:/mcp-servers-config.json
916 toolcallback:
917 enabled: true
918 anthropic:
919 api-key: ${ANTHROPIC_API_KEY}
920```
921 
922This activates the `spring-ai-starter-mcp-client` to create one or more `McpClient`s based on the provided server configuration.
923The `spring.ai.mcp.client.toolcallback.enabled=true` property enables the tool callback mechanism, that automatically registers all MCP tool as spring ai tools.
924It is disabled by default.
925 
9263. MCP Server Configuration (`mcp-servers-config.json`):
927 
928```json theme={null}
929{
930 "mcpServers": {
931 "brave-search": {
932 "command": "npx",
933 "args": ["-y", "@modelcontextprotocol/server-brave-search"],
934 "env": {
935 "BRAVE_API_KEY": "<PUT YOUR BRAVE API KEY>"
699936 }
700937 }
701 
702 async cleanup() {
703 await this.mcp.close();
938 }
939}
940```
941 
942### Chat Implementation
943 
944The chatbot is implemented using Spring AI's ChatClient with MCP tool integration:
945 
946```java theme={null}
947var chatClient = chatClientBuilder
948 .defaultSystem("You are useful assistant, expert in AI and Java.")
949 .defaultToolCallbacks((Object[]) mcpToolAdapter.toolCallbacks())
950 .defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory()))
951 .build();
952```
953 
954Key features:
955 
956* Uses Claude AI model for natural language understanding
957* Integrates Brave Search through MCP for real-time web search capabilities
958* Maintains conversation memory using InMemoryChatMemory
959* Runs as an interactive command-line application
960 
961### Build and run
962 
963```bash theme={null}
964./mvnw clean install
965java -jar ./target/ai-mcp-brave-chatbot-0.0.1-SNAPSHOT.jar
966```
967 
968or
969 
970```bash theme={null}
971./mvnw spring-boot:run
972```
973 
974The application will start an interactive chat session where you can ask questions. The chatbot will use Brave Search when it needs to find information from the internet to answer your queries.
975 
976The chatbot can:
977 
978* Answer questions using its built-in knowledge
979* Perform web searches when needed using Brave Search
980* Remember context from previous messages in the conversation
981* Combine information from multiple sources to provide comprehensive answers
982 
983### Advanced Configuration
984 
985The MCP client supports additional configuration options:
986 
987* Client customization through `McpClientCustomizer<McpClient.SyncSpec>` or `McpClientCustomizer<McpClient.AsyncSpec>` beans
988* Multiple clients with multiple transport types: `STDIO` and Streamable HTTP
989* Integration with Spring AI's tool execution framework
990* Automatic client initialization and lifecycle management
991 
992To connect to a remote MCP server over Streamable HTTP, configure a connection URL:
993 
994```properties theme={null}
995spring.ai.mcp.client.streamable-http.connections.server1.url=http://localhost:8080
996```
997 
998For WebFlux-based applications, you can use the WebFlux starter instead:
999 
1000```xml theme={null}
1001<dependency>
1002 <groupId>org.springframework.ai</groupId>
1003 <artifactId>spring-ai-starter-mcp-client-webflux</artifactId>
1004</dependency>
1005```
1006 
1007This provides similar functionality but uses a WebFlux-based Streamable HTTP transport implementation, recommended for production deployments.
1008 
1009**Kotlin**
1010 
1011[You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/kotlin-mcp-client)
1012 
1013## System Requirements
1014 
1015Before starting, ensure your system meets these requirements:
1016 
1017* JDK 11 or higher
1018* Anthropic API key (Claude)
1019 
1020## Setting up your environment
1021 
1022First, let's install `java` and `gradle` if you haven't already.
1023You can download `java` from [official Oracle JDK website](https://www.oracle.com/java/technologies/downloads/).
1024Verify your `java` installation:
1025 
1026```bash theme={null}
1027java --version
1028```
1029 
1030Now, let's create and set up your project:
1031 
1032```bash macOS/Linux theme={null}
1033# Create a new directory for our project
1034mkdir kotlin-mcp-client
1035cd kotlin-mcp-client
1036 
1037# Initialize a new kotlin project
1038gradle init
1039```
1040 
1041```powershell Windows theme={null}
1042# Create a new directory for our project
1043md kotlin-mcp-client
1044cd kotlin-mcp-client
1045# Initialize a new kotlin project
1046gradle init
1047```
1048 
1049After running `gradle init`, select **Application** as the project type, **Kotlin** as the programming language.
1050 
1051Alternatively, you can create a Kotlin application using the [IntelliJ IDEA project wizard](https://kotlinlang.org/docs/jvm-get-started.html).
1052 
1053After creating the project, replace the contents of your `build.gradle.kts` with:
1054 
1055```kotlin build.gradle.kts theme={null}
1056// Check latest versions at https://github.com/modelcontextprotocol/kotlin-sdk/releases
1057val mcpVersion = "0.9.0"
1058val ktorVersion = "3.2.3"
1059val anthropicVersion = "2.15.0"
1060val slf4jVersion = "2.0.17"
1061 
1062plugins {
1063 kotlin("jvm") version "2.3.20"
1064 id("com.gradleup.shadow") version "8.3.9"
1065 application
1066}
1067 
1068application {
1069 mainClass.set("MainKt")
1070}
1071 
1072dependencies {
1073 implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion")
1074 implementation("io.ktor:ktor-client-cio:$ktorVersion")
1075 implementation("com.anthropic:anthropic-java:$anthropicVersion")
1076 implementation("org.slf4j:slf4j-simple:$slf4jVersion")
1077}
1078```
1079 
1080Verify that everything is set up correctly:
1081 
1082```bash theme={null}
1083./gradlew build
1084```
1085 
1086## Setting up your API key
1087 
1088You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
1089 
1090Set up your API key:
1091 
1092```bash theme={null}
1093export ANTHROPIC_API_KEY='your-anthropic-api-key-here'
1094```
1095 
1096> [!WARNING]
1097>
1098> Make sure you keep your `ANTHROPIC_API_KEY` secure!
1099 
1100## Creating the Client
1101 
1102### Basic Client Structure
1103 
1104First, let's create the basic client class:
1105 
1106```kotlin theme={null}
1107class MCPClient(apiKey: String) : AutoCloseable {
1108 private val anthropic = AnthropicOkHttpClient.builder()
1109 .apiKey(apiKey)
1110 .build()
1111 
1112 private val mcp: Client = Client(
1113 clientInfo = Implementation(name = "mcp-client-cli", version = "1.0.0")
1114 )
1115 private var serverProcess: Process? = null
1116 private lateinit var tools: List<ToolUnion>
1117 
1118 // methods will go here
1119 
1120 override fun close() {
1121 runBlocking {
1122 mcp.close()
1123 }
1124 serverProcess?.destroy()
1125 anthropic.close()
7041126 }
705 ```
706 
707 ### Main Entry Point
708 
709 Finally, we'll add the main execution logic:
710 
711 ```typescript theme={null}
712 async function main() {
713 if (process.argv.length < 3) {
714 console.log("Usage: node index.ts <path_to_server_script>");
715 return;
716 }
717 const mcpClient = new MCPClient();
718 try {
719 await mcpClient.connectToServer(process.argv[2]);
720 await mcpClient.chatLoop();
721 } catch (e) {
722 console.error("Error:", e);
723 await mcpClient.cleanup();
724 process.exit(1);
725 } finally {
726 await mcpClient.cleanup();
727 process.exit(0);
728 }
1127}
1128```
1129 
1130### Server connection management
1131 
1132Next, we'll implement the method to connect to an MCP server:
1133 
1134```kotlin theme={null}
1135suspend fun connectToServer(serverScriptPath: String) {
1136 val command = buildList {
1137 when (serverScriptPath.substringAfterLast(".")) {
1138 "js" -> add("node")
1139 "py" -> add(if (System.getProperty("os.name").lowercase().contains("win")) "python" else "python3")
1140 "jar" -> addAll(listOf("java", "-jar"))
1141 else -> throw IllegalArgumentException("Server script must be a .js, .py or .jar file")
1142 }
1143 add(serverScriptPath)
7291144 }
7301145 
731 main();
732 ```
733 
734 ## Running the Client
735 
736 To run your client with any MCP server:
737 
738 ```bash theme={null}
739 # Build TypeScript
740 npm run build
741 
742 # Run the client
743 node build/index.js path/to/server.py # python server
744 node build/index.js path/to/build/index.js # node server
745 ```
746 
747 <Note>
748 If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript), your command might look something like this: `node build/index.js .../quickstart-resources/weather-server-typescript/build/index.js`
749 </Note>
750 
751 **The client will:**
752 
753 1. Connect to the specified server
754 2. List available tools
755 3. Start an interactive chat session where you can:
756 * Enter queries
757 * See tool executions
758 * Get responses from Claude
759 
760 ## How It Works
761 
762 When you submit a query:
763 
764 1. The client gets the list of available tools from the server
765 2. Your query is sent to Claude along with tool descriptions
766 3. Claude decides which tools (if any) to use
767 4. The client executes any requested tool calls through the server
768 5. Results are sent back to Claude
769 6. Claude provides a natural language response
770 7. The response is displayed to you
771 
772 ## Best practices
773 
774 1. **Error Handling**
775 * Use TypeScript's type system for better error detection
776 * Wrap tool calls in try-catch blocks
777 * Provide meaningful error messages
778 * Gracefully handle connection issues
779 
780 2. **Security**
781 * Store API keys securely in `.env`
782 * Validate server responses
783 * Be cautious with tool permissions
784 
785 ## Troubleshooting
786 
787 ### Server Path Issues
788 
789 * Double-check the path to your server script is correct
790 * Use the absolute path if the relative path isn't working
791 * For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
792 * Verify the server file has the correct extension (.js for Node.js or .py for Python)
793 
794 Example of correct path usage:
795 
796 ```bash theme={null}
797 # Relative path
798 node build/index.js ./server/build/index.js
799 
800 # Absolute path
801 node build/index.js /Users/username/projects/mcp-server/build/index.js
802 
803 # Windows path (either format works)
804 node build/index.js C:/projects/mcp-server/build/index.js
805 node build/index.js C:\\projects\\mcp-server\\build\\index.js
806 ```
807 
808 ### Response Timing
809 
810 * The first response might take up to 30 seconds to return
811 * This is normal and happens while:
812 * The server initializes
813 * Claude processes the query
814 * Tools are being executed
815 * Subsequent responses are typically faster
816 * Don't interrupt the process during this initial waiting period
817 
818 ### Common Error Messages
819 
820 If you see:
821 
822 * `Error: Cannot find module`: Check your build folder and ensure TypeScript compilation succeeded
823 * `Connection refused`: Ensure the server is running and the path is correct
824 * `Tool execution failed`: Verify the tool's required environment variables are set
825 * `ANTHROPIC_API_KEY is not set`: Check your .env file and environment variables
826 * `TypeError`: Ensure you're using the correct types for tool arguments
827 * `BadRequestError`: Ensure you have enough credits to access the Anthropic API
828 </Tab>
829 
830 <Tab title="Java">
831 <Note>
832 This is a quickstart demo based on Spring AI MCP auto-configuration and boot starters.
833 To learn how to create sync and async MCP Clients manually, consult the [Java SDK Client](https://java.sdk.modelcontextprotocol.io/) documentation.
834 </Note>
835 
836 This example demonstrates how to build an interactive chatbot that combines Spring AI's Model Context Protocol (MCP) with the [Brave Search MCP Server](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/brave-search). The application creates a conversational interface powered by Anthropic's Claude AI model that can perform internet searches through Brave Search, enabling natural language interactions with real-time web data.
837 [You can find the complete code for this tutorial here.](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/web-search/brave-chatbot)
838 
839 ## System Requirements
840 
841 Before starting, ensure your system meets these requirements:
842 
843 * Java 17 or higher
844 * Maven 3.6+
845 * npx package manager
846 * Anthropic API key (Claude)
847 * Brave Search API key
848 
849 ## Setting Up Your Environment
850 
851 1. Install npx (Node Package eXecute):
852 First, make sure to install [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)
853 and then run:
854 
855 ```bash theme={null}
856 npm install -g npx
857 ```
858 
859 2. Clone the repository:
860 
861 ```bash theme={null}
862 git clone https://github.com/spring-projects/spring-ai-examples.git
863 cd model-context-protocol/web-search/brave-chatbot
864 ```
865 
866 3. Set up your API keys:
867 
868 ```bash theme={null}
869 export ANTHROPIC_API_KEY='your-anthropic-api-key-here'
870 export BRAVE_API_KEY='your-brave-api-key-here'
871 ```
872 
873 4. Build the application:
874 
875 ```bash theme={null}
876 ./mvnw clean install
877 ```
878 
879 5. Run the application using Maven:
880 ```bash theme={null}
881 ./mvnw spring-boot:run
882 ```
883 
884 <Warning>
885 Make sure you keep your `ANTHROPIC_API_KEY` and `BRAVE_API_KEY` keys secure!
886 </Warning>
887 
888 ## How it Works
889 
890 The application integrates Spring AI with the Brave Search MCP server through several components:
891 
892 ### MCP Client Configuration
893 
894 1. Required dependencies in pom.xml:
895 
896 ```xml theme={null}
897 <dependency>
898 <groupId>org.springframework.ai</groupId>
899 <artifactId>spring-ai-starter-mcp-client</artifactId>
900 </dependency>
901 <dependency>
902 <groupId>org.springframework.ai</groupId>
903 <artifactId>spring-ai-starter-model-anthropic</artifactId>
904 </dependency>
905 ```
906 
907 2. Application properties (application.yml):
908 
909 ```yml theme={null}
910 spring:
911 ai:
912 mcp:
913 client:
914 enabled: true
915 name: brave-search-client
916 version: 1.0.0
917 type: SYNC
918 request-timeout: 20s
919 stdio:
920 root-change-notification: true
921 servers-configuration: classpath:/mcp-servers-config.json
922 toolcallback:
923 enabled: true
924 anthropic:
925 api-key: ${ANTHROPIC_API_KEY}
926 ```
927 
928 This activates the `spring-ai-starter-mcp-client` to create one or more `McpClient`s based on the provided server configuration.
929 The `spring.ai.mcp.client.toolcallback.enabled=true` property enables the tool callback mechanism, that automatically registers all MCP tool as spring ai tools.
930 It is disabled by default.
931 
932 3. MCP Server Configuration (`mcp-servers-config.json`):
933 
934 ```json theme={null}
935 {
936 "mcpServers": {
937 "brave-search": {
938 "command": "npx",
939 "args": ["-y", "@modelcontextprotocol/server-brave-search"],
940 "env": {
941 "BRAVE_API_KEY": "<PUT YOUR BRAVE API KEY>"
942 }
943 }
944 }
945 }
946 ```
947 
948 ### Chat Implementation
949 
950 The chatbot is implemented using Spring AI's ChatClient with MCP tool integration:
951 
952 ```java theme={null}
953 var chatClient = chatClientBuilder
954 .defaultSystem("You are useful assistant, expert in AI and Java.")
955 .defaultToolCallbacks((Object[]) mcpToolAdapter.toolCallbacks())
956 .defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory()))
957 .build();
958 ```
959 
960 Key features:
961 
962 * Uses Claude AI model for natural language understanding
963 * Integrates Brave Search through MCP for real-time web search capabilities
964 * Maintains conversation memory using InMemoryChatMemory
965 * Runs as an interactive command-line application
966 
967 ### Build and run
968 
969 ```bash theme={null}
970 ./mvnw clean install
971 java -jar ./target/ai-mcp-brave-chatbot-0.0.1-SNAPSHOT.jar
972 ```
973 
974 or
975 
976 ```bash theme={null}
977 ./mvnw spring-boot:run
978 ```
979 
980 The application will start an interactive chat session where you can ask questions. The chatbot will use Brave Search when it needs to find information from the internet to answer your queries.
981 
982 The chatbot can:
983 
984 * Answer questions using its built-in knowledge
985 * Perform web searches when needed using Brave Search
986 * Remember context from previous messages in the conversation
987 * Combine information from multiple sources to provide comprehensive answers
988 
989 ### Advanced Configuration
990 
991 The MCP client supports additional configuration options:
992 
993 * Client customization through `McpClientCustomizer<McpClient.SyncSpec>` or `McpClientCustomizer<McpClient.AsyncSpec>` beans
994 * Multiple clients with multiple transport types: `STDIO` and Streamable HTTP
995 * Integration with Spring AI's tool execution framework
996 * Automatic client initialization and lifecycle management
997 
998 To connect to a remote MCP server over Streamable HTTP, configure a connection URL:
999 
1000 ```properties theme={null}
1001 spring.ai.mcp.client.streamable-http.connections.server1.url=http://localhost:8080
1002 ```
1003 
1004 For WebFlux-based applications, you can use the WebFlux starter instead:
1005 
1006 ```xml theme={null}
1007 <dependency>
1008 <groupId>org.springframework.ai</groupId>
1009 <artifactId>spring-ai-starter-mcp-client-webflux</artifactId>
1010 </dependency>
1011 ```
1012 
1013 This provides similar functionality but uses a WebFlux-based Streamable HTTP transport implementation, recommended for production deployments.
1014 </Tab>
1015 
1016 <Tab title="Kotlin">
1017 [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/kotlin-mcp-client)
1018 
1019 ## System Requirements
1020 
1021 Before starting, ensure your system meets these requirements:
1022 
1023 * JDK 11 or higher
1024 * Anthropic API key (Claude)
1025 
1026 ## Setting up your environment
1027 
1028 First, let's install `java` and `gradle` if you haven't already.
1029 You can download `java` from [official Oracle JDK website](https://www.oracle.com/java/technologies/downloads/).
1030 Verify your `java` installation:
1031 
1032 ```bash theme={null}
1033 java --version
1034 ```
1035 
1036 Now, let's create and set up your project:
1037 
1038 <CodeGroup>
1039 ```bash macOS/Linux theme={null}
1040 # Create a new directory for our project
1041 mkdir kotlin-mcp-client
1042 cd kotlin-mcp-client
1043 
1044 # Initialize a new kotlin project
1045 gradle init
1046 ```
1047 
1048 ```powershell Windows theme={null}
1049 # Create a new directory for our project
1050 md kotlin-mcp-client
1051 cd kotlin-mcp-client
1052 # Initialize a new kotlin project
1053 gradle init
1054 ```
1055 </CodeGroup>
1056 
1057 After running `gradle init`, select **Application** as the project type, **Kotlin** as the programming language.
1058 
1059 Alternatively, you can create a Kotlin application using the [IntelliJ IDEA project wizard](https://kotlinlang.org/docs/jvm-get-started.html).
1060 
1061 After creating the project, replace the contents of your `build.gradle.kts` with:
1062 
1063 ```kotlin build.gradle.kts theme={null}
1064 // Check latest versions at https://github.com/modelcontextprotocol/kotlin-sdk/releases
1065 val mcpVersion = "0.9.0"
1066 val ktorVersion = "3.2.3"
1067 val anthropicVersion = "2.15.0"
1068 val slf4jVersion = "2.0.17"
1069 
1070 plugins {
1071 kotlin("jvm") version "2.3.20"
1072 id("com.gradleup.shadow") version "8.3.9"
1073 application
1074 }
1075 
1076 application {
1077 mainClass.set("MainKt")
1078 }
1079 
1080 dependencies {
1081 implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion")
1082 implementation("io.ktor:ktor-client-cio:$ktorVersion")
1083 implementation("com.anthropic:anthropic-java:$anthropicVersion")
1084 implementation("org.slf4j:slf4j-simple:$slf4jVersion")
1085 }
1086 ```
1087 
1088 Verify that everything is set up correctly:
1089 
1090 ```bash theme={null}
1091 ./gradlew build
1092 ```
1093 
1094 ## Setting up your API key
1095 
1096 You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
1097 
1098 Set up your API key:
1099 
1100 ```bash theme={null}
1101 export ANTHROPIC_API_KEY='your-anthropic-api-key-here'
1102 ```
1103 
1104 <Warning>
1105 Make sure you keep your `ANTHROPIC_API_KEY` secure!
1106 </Warning>
1107 
1108 ## Creating the Client
1109 
1110 ### Basic Client Structure
1111 
1112 First, let's create the basic client class:
1113 
1114 ```kotlin theme={null}
1115 class MCPClient(apiKey: String) : AutoCloseable {
1116 private val anthropic = AnthropicOkHttpClient.builder()
1117 .apiKey(apiKey)
1118 .build()
1119 
1120 private val mcp: Client = Client(
1121 clientInfo = Implementation(name = "mcp-client-cli", version = "1.0.0")
1122 )
1123 private var serverProcess: Process? = null
1124 private lateinit var tools: List<ToolUnion>
1125 
1126 // methods will go here
1127 
1128 override fun close() {
1129 runBlocking {
1130 mcp.close()
1131 }
1132 serverProcess?.destroy()
1133 anthropic.close()
1134 }
1135 }
1136 ```
1137 
1138 ### Server connection management
1139 
1140 Next, we'll implement the method to connect to an MCP server:
1141 
1142 ```kotlin theme={null}
1143 suspend fun connectToServer(serverScriptPath: String) {
1144 val command = buildList {
1145 when (serverScriptPath.substringAfterLast(".")) {
1146 "js" -> add("node")
1147 "py" -> add(if (System.getProperty("os.name").lowercase().contains("win")) "python" else "python3")
1148 "jar" -> addAll(listOf("java", "-jar"))
1149 else -> throw IllegalArgumentException("Server script must be a .js, .py or .jar file")
1150 }
1151 add(serverScriptPath)
1152 }
1153 
1154 val process = ProcessBuilder(command).start()
1155 serverProcess = process
1156 
1157 val transport = StdioClientTransport(
1158 input = process.inputStream.asSource().buffered(),
1159 output = process.outputStream.asSink().buffered(),
1160 )
1161 
1162 mcp.connect(transport)
1163 
1164 val toolsResult = mcp.listTools()
1165 tools = toolsResult.tools.map { tool ->
1166 ToolUnion.ofTool(
1167 Tool.builder()
1168 .name(tool.name)
1169 .description(tool.description ?: "")
1170 .inputSchema(
1171 Tool.InputSchema.builder()
1172 .type(JsonValue.from(tool.inputSchema.type))
1173 .properties(tool.inputSchema.properties?.toJsonValue() ?: EmptyJsonObject.toJsonValue())
1174 .putAdditionalProperty("required", JsonValue.from(tool.inputSchema.required))
1175 .build(),
1176 )
1177 .build(),
1178 )
1179 }
1180 println("Connected to server with tools: ${tools.joinToString(", ") { it.tool().get().name() }}")
1181 }
1182 ```
1183 
1184 <Accordion title="JsonObject.toJsonValue() helper">
1185 This helper converts a kotlinx.serialization `JsonObject` to an Anthropic SDK `JsonValue` using Jackson:
1186 
1187 ```kotlin theme={null}
1188 private fun JsonObject.toJsonValue(): JsonValue {
1189 val mapper = ObjectMapper()
1190 val node = mapper.readTree(this.toString())
1191 return JsonValue.fromJsonNode(node)
1192 }
1193 ```
1194 </Accordion>
1195 
1196 ### Query processing logic
1197 
1198 Now let's add the core functionality for processing queries and handling tool calls:
1199 
1200 ```kotlin theme={null}
1201 suspend fun processQuery(query: String): String {
1202 val messages = mutableListOf(
1203 MessageParam.builder()
1204 .role(MessageParam.Role.USER)
1205 .content(query)
1146 val process = ProcessBuilder(command).start()
1147 serverProcess = process
1148 
1149 val transport = StdioClientTransport(
1150 input = process.inputStream.asSource().buffered(),
1151 output = process.outputStream.asSink().buffered(),
1152 )
1153 
1154 mcp.connect(transport)
1155 
1156 val toolsResult = mcp.listTools()
1157 tools = toolsResult.tools.map { tool ->
1158 ToolUnion.ofTool(
1159 Tool.builder()
1160 .name(tool.name)
1161 .description(tool.description ?: "")
1162 .inputSchema(
1163 Tool.InputSchema.builder()
1164 .type(JsonValue.from(tool.inputSchema.type))
1165 .properties(tool.inputSchema.properties?.toJsonValue() ?: EmptyJsonObject.toJsonValue())
1166 .putAdditionalProperty("required", JsonValue.from(tool.inputSchema.required))
1167 .build(),
1168 )
12061169 .build(),
12071170 )
1208 
1209 val response = anthropic.messages().create(
1210 MessageCreateParams.builder()
1211 .model("claude-opus-5")
1212 .maxTokens(1024)
1213 .messages(messages)
1214 .tools(tools)
1215 .build(),
1216 )
1217 
1218 val finalText = mutableListOf<String>()
1219 response.content().forEach { content ->
1220 when {
1221 content.isText() -> finalText.add(content.text().get().text())
1222 
1223 content.isToolUse() -> {
1224 val toolName = content.toolUse().get().name()
1225 val toolArgs =
1226 content.toolUse().get()._input().convert(object : TypeReference<Map<String, JsonValue>>() {})
1227 
1228 val result = mcp.callTool(
1229 name = toolName,
1230 arguments = toolArgs ?: emptyMap(),
1231 )
1232 finalText.add("[Calling tool $toolName with args $toolArgs]")
1233 
1234 messages.add(
1235 MessageParam.builder()
1236 .role(MessageParam.Role.USER)
1237 .content(
1238 result.content
1239 .filterIsInstance<TextContent>()
1240 .joinToString("\n") { it.text }
1241 )
1242 .build(),
1243 )
1244 
1245 val aiResponse = anthropic.messages().create(
1246 MessageCreateParams.builder()
1247 .model("claude-opus-5")
1248 .maxTokens(1024)
1249 .messages(messages)
1250 .build(),
1251 )
1252 
1253 finalText.add(aiResponse.content().first().text().get().text())
1254 }
1255 }
1256 }
1257 
1258 return finalText.joinToString("\n")
12591171 }
1260 ```
1261 
1262 ### Interactive chat
1263 
1264 We'll add the chat loop:
1265 
1266 ```kotlin theme={null}
1267 suspend fun chatLoop() {
1268 println("\nMCP Client Started!")
1269 println("Type your queries or 'quit' to exit.")
1270 
1271 while (true) {
1272 print("\nQuery: ")
1273 val message = readlnOrNull() ?: break
1274 if (message.trim().lowercase() == "quit") break
1275 
1276 try {
1277 val response = processQuery(message)
1278 println("\n$response")
1279 } catch (e: Exception) {
1280 println("\nError: ${e.message}")
1172 println("Connected to server with tools: ${tools.joinToString(", ") { it.tool().get().name() }}")
1173}
1174```
1175 
1176> **JsonObject.toJsonValue() helper**
1177>
1178> This helper converts a kotlinx.serialization `JsonObject` to an Anthropic SDK `JsonValue` using Jackson:
1179>
1180> ```kotlin theme={null}
1181> private fun JsonObject.toJsonValue(): JsonValue {
1182> val mapper = ObjectMapper()
1183> val node = mapper.readTree(this.toString())
1184> return JsonValue.fromJsonNode(node)
1185> }
1186> ```
1187 
1188### Query processing logic
1189 
1190Now let's add the core functionality for processing queries and handling tool calls:
1191 
1192```kotlin theme={null}
1193suspend fun processQuery(query: String): String {
1194 val messages = mutableListOf(
1195 MessageParam.builder()
1196 .role(MessageParam.Role.USER)
1197 .content(query)
1198 .build(),
1199 )
1200 
1201 val response = anthropic.messages().create(
1202 MessageCreateParams.builder()
1203 .model("claude-opus-5")
1204 .maxTokens(1024)
1205 .messages(messages)
1206 .tools(tools)
1207 .build(),
1208 )
1209 
1210 val finalText = mutableListOf<String>()
1211 response.content().forEach { content ->
1212 when {
1213 content.isText() -> finalText.add(content.text().get().text())
1214 
1215 content.isToolUse() -> {
1216 val toolName = content.toolUse().get().name()
1217 val toolArgs =
1218 content.toolUse().get()._input().convert(object : TypeReference<Map<String, JsonValue>>() {})
1219 
1220 val result = mcp.callTool(
1221 name = toolName,
1222 arguments = toolArgs ?: emptyMap(),
1223 )
1224 finalText.add("[Calling tool $toolName with args $toolArgs]")
1225 
1226 messages.add(
1227 MessageParam.builder()
1228 .role(MessageParam.Role.USER)
1229 .content(
1230 result.content
1231 .filterIsInstance<TextContent>()
1232 .joinToString("\n") { it.text }
1233 )
1234 .build(),
1235 )
1236 
1237 val aiResponse = anthropic.messages().create(
1238 MessageCreateParams.builder()
1239 .model("claude-opus-5")
1240 .maxTokens(1024)
1241 .messages(messages)
1242 .build(),
1243 )
1244 
1245 finalText.add(aiResponse.content().first().text().get().text())
12811246 }
12821247 }
12831248 }
1284 ```
1285 
1286 ### Main entry point
1287 
1288 Finally, we'll add the main execution function:
1289 
1290 ```kotlin theme={null}
1291 fun main(args: Array<String>) = runBlocking {
1292 require(args.isNotEmpty()) { "Usage: java -jar <path> <path_to_server_script>" }
1293 
1294 val apiKey = System.getenv("ANTHROPIC_API_KEY")
1295 require(!apiKey.isNullOrBlank()) { "ANTHROPIC_API_KEY environment variable is not set" }
1296 
1297 val client = MCPClient(apiKey)
1298 client.use {
1299 client.connectToServer(args.first())
1300 client.chatLoop()
1249 
1250 return finalText.joinToString("\n")
1251}
1252```
1253 
1254### Interactive chat
1255 
1256We'll add the chat loop:
1257 
1258```kotlin theme={null}
1259suspend fun chatLoop() {
1260 println("\nMCP Client Started!")
1261 println("Type your queries or 'quit' to exit.")
1262 
1263 while (true) {
1264 print("\nQuery: ")
1265 val message = readlnOrNull() ?: break
1266 if (message.trim().lowercase() == "quit") break
1267 
1268 try {
1269 val response = processQuery(message)
1270 println("\n$response")
1271 } catch (e: Exception) {
1272 println("\nError: ${e.message}")
13011273 }
13021274 }
1303 ```
1304 
1305 ## Running the client
1306 
1307 To run your client with any MCP server:
1308 
1309 ```bash theme={null}
1310 ./gradlew build
1311 
1312 # Run the client
1313 java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar path/to/server.jar # JVM server
1314 java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar path/to/server.py # Python server
1315 java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar path/to/build/index.js # Node server
1316 ```
1317 
1318 Alternatively, you can run directly with Gradle:
1319 
1320 ```bash theme={null}
1321 ./gradlew run --args="path/to/server.jar"
1322 ```
1323 
1324 <Note>
1325 If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar .../samples/weather-stdio-server/build/libs/weather-stdio-server-0.1.0-all.jar`
1326 </Note>
1327 
1328 **The client will:**
1329 
1330 1. Connect to the specified server
1331 2. List available tools
1332 3. Start an interactive chat session where you can:
1333 * Enter queries
1334 * See tool executions
1335 * Get responses from Claude
1336 
1337 ## How it works
1338 
1339 Here's a high-level workflow schema:
1340 
1341 ```mermaid theme={null}
1342 ---
1343 config:
1344 theme: neutral
1345 ---
1346 sequenceDiagram
1347 actor User
1348 participant Client
1349 participant Claude
1350 participant MCP_Server as MCP Server
1351 participant Tools
1352 
1353 User->>Client: Send query
1354 Client<<->>MCP_Server: Get available tools
1355 Client->>Claude: Send query with tool descriptions
1356 Claude-->>Client: Decide tool execution
1357 Client->>MCP_Server: Request tool execution
1358 MCP_Server->>Tools: Execute chosen tools
1359 Tools-->>MCP_Server: Return results
1360 MCP_Server-->>Client: Send results
1361 Client->>Claude: Send tool results
1362 Claude-->>Client: Provide final response
1363 Client-->>User: Display response
1364 ```
1365 
1366 When you submit a query:
1367 
1368 1. The client gets the list of available tools from the server
1369 2. Your query is sent to Claude along with tool descriptions
1370 3. Claude decides which tools (if any) to use
1371 4. The client executes any requested tool calls through the server
1372 5. Results are sent back to Claude
1373 6. Claude provides a natural language response
1374 7. The response is displayed to you
1375 
1376 ## Best practices
1377 
1378 1. **Error Handling**
1379 * Leverage Kotlin's type system to model errors explicitly
1380 * Wrap external tool and API calls in `try-catch` blocks when exceptions are possible
1381 * Provide clear and meaningful error messages
1382 * Handle network timeouts and connection issues gracefully
1383 
1384 2. **Security**
1385 * Store API keys and secrets securely in `local.properties`, environment variables, or secret managers
1386 * Validate all external responses to avoid unexpected or unsafe data usage
1387 * Be cautious with permissions and trust boundaries when using tools
1388 
1389 3. **Environment**
1390 * Set `ANTHROPIC_API_KEY` through environment variables rather than hardcoding
1391 * Use `.env` files with appropriate `.gitignore` rules for local development
1392 
1393 ## Troubleshooting
1394 
1395 ### Server Path Issues
1396 
1397 * Double-check the path to your server script is correct
1398 * Use the absolute path if the relative path isn't working
1399 * For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
1400 * Make sure that the required runtime is installed (java for Java, npm for Node.js, or uv for Python)
1401 * Verify the server file has the correct extension (.jar for Java, .js for Node.js or .py for Python)
1402 
1403 Example of correct path usage:
1404 
1405 ```bash theme={null}
1406 # Relative path
1407 java -jar build/libs/client.jar ./server/build/libs/server.jar
1408 
1409 # Absolute path
1410 java -jar build/libs/client.jar /Users/username/projects/mcp-server/build/libs/server.jar
1411 
1412 # Windows path (either format works)
1413 java -jar build/libs/client.jar C:/projects/mcp-server/build/libs/server.jar
1414 java -jar build/libs/client.jar C:\\projects\\mcp-server\\build\\libs\\server.jar
1415 ```
1416 
1417 ### Build Issues
1418 
1419 * Use `./gradlew build` or `./gradlew shadowJar` (not `./gradlew jar`) to create the shadow JAR with all dependencies
1420 * If you get JDK version errors, ensure your installed JDK version matches or exceeds the `jvmToolchain` setting in `build.gradle.kts`
1421 
1422 ### Response Timing
1423 
1424 * The first response might take up to 30 seconds to return
1425 * This is normal and happens while:
1426 * The server initializes
1427 * Claude processes the query
1428 * Tools are being executed
1429 * Subsequent responses are typically faster
1430 * Don't interrupt the process during this initial waiting period
1431 
1432 ### Common Error Messages
1433 
1434 If you see:
1435 
1436 * `Connection refused`: Ensure the server is running and the path is correct
1437 * `Tool execution failed`: Verify the tool's required environment variables are set
1438 * `ANTHROPIC_API_KEY is not set`: Check your environment variables
1439 </Tab>
1440 
1441 <Tab title="C#">
1442 [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/csharp-sdk/tree/main/samples/QuickstartClient)
1443 
1444 ## System Requirements
1445 
1446 Before starting, ensure your system meets these requirements:
1447 
1448 * .NET 8.0 or higher
1449 * Anthropic API key (Claude)
1450 * Windows, Linux, or macOS
1451 
1452 ## Setting up your environment
1453 
1454 First, create a new .NET project:
1455 
1456 ```bash theme={null}
1457 dotnet new console -n QuickstartClient
1458 cd QuickstartClient
1459 ```
1460 
1461 Then, add the required dependencies to your project:
1462 
1463 ```bash theme={null}
1464 dotnet add package ModelContextProtocol --prerelease
1465 dotnet add package Anthropic.SDK
1466 dotnet add package Microsoft.Extensions.Hosting
1467 dotnet add package Microsoft.Extensions.AI
1468 ```
1469 
1470 ## Setting up your API key
1471 
1472 You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
1473 
1474 ```bash theme={null}
1475 dotnet user-secrets init
1476 dotnet user-secrets set "ANTHROPIC_API_KEY" "<your key here>"
1477 ```
1478 
1479 ## Creating the Client
1480 
1481 ### Basic Client Structure
1482 
1483 First, let's setup the basic client class in the file `Program.cs`:
1484 
1485 ```csharp theme={null}
1486 using Anthropic.SDK;
1487 using Microsoft.Extensions.AI;
1488 using Microsoft.Extensions.Configuration;
1489 using Microsoft.Extensions.Hosting;
1490 using ModelContextProtocol.Client;
1491 using ModelContextProtocol.Protocol.Transport;
1492 
1493 var builder = Host.CreateApplicationBuilder(args);
1494 
1495 builder.Configuration
1496 .AddEnvironmentVariables()
1497 .AddUserSecrets<Program>();
1498 ```
1499 
1500 This creates the beginnings of a .NET console application that can read the API key from user secrets.
1501 
1502 Next, we'll setup the MCP Client:
1503 
1504 ```csharp theme={null}
1505 var (command, arguments) = GetCommandAndArguments(args);
1506 
1507 var clientTransport = new StdioClientTransport(new()
1275}
1276```
1277 
1278### Main entry point
1279 
1280Finally, we'll add the main execution function:
1281 
1282```kotlin theme={null}
1283fun main(args: Array<String>) = runBlocking {
1284 require(args.isNotEmpty()) { "Usage: java -jar <path> <path_to_server_script>" }
1285 
1286 val apiKey = System.getenv("ANTHROPIC_API_KEY")
1287 require(!apiKey.isNullOrBlank()) { "ANTHROPIC_API_KEY environment variable is not set" }
1288 
1289 val client = MCPClient(apiKey)
1290 client.use {
1291 client.connectToServer(args.first())
1292 client.chatLoop()
1293 }
1294}
1295```
1296 
1297## Running the client
1298 
1299To run your client with any MCP server:
1300 
1301```bash theme={null}
1302./gradlew build
1303 
1304# Run the client
1305java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar path/to/server.jar # JVM server
1306java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar path/to/server.py # Python server
1307java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar path/to/build/index.js # Node server
1308```
1309 
1310Alternatively, you can run directly with Gradle:
1311 
1312```bash theme={null}
1313./gradlew run --args="path/to/server.jar"
1314```
1315 
1316> [!NOTE]
1317>
1318> If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar .../samples/weather-stdio-server/build/libs/weather-stdio-server-0.1.0-all.jar`
1319 
1320**The client will:**
1321 
13221. Connect to the specified server
13232. List available tools
13243. Start an interactive chat session where you can:
1325 * Enter queries
1326 * See tool executions
1327 * Get responses from Claude
1328 
1329## How it works
1330 
1331Here's a high-level workflow schema:
1332 
1333```mermaid theme={null}
1334---
1335config:
1336 theme: neutral
1337---
1338sequenceDiagram
1339 actor User
1340 participant Client
1341 participant Claude
1342 participant MCP_Server as MCP Server
1343 participant Tools
1344 
1345 User->>Client: Send query
1346 Client<<->>MCP_Server: Get available tools
1347 Client->>Claude: Send query with tool descriptions
1348 Claude-->>Client: Decide tool execution
1349 Client->>MCP_Server: Request tool execution
1350 MCP_Server->>Tools: Execute chosen tools
1351 Tools-->>MCP_Server: Return results
1352 MCP_Server-->>Client: Send results
1353 Client->>Claude: Send tool results
1354 Claude-->>Client: Provide final response
1355 Client-->>User: Display response
1356```
1357 
1358When you submit a query:
1359 
13601. The client gets the list of available tools from the server
13612. Your query is sent to Claude along with tool descriptions
13623. Claude decides which tools (if any) to use
13634. The client executes any requested tool calls through the server
13645. Results are sent back to Claude
13656. Claude provides a natural language response
13667. The response is displayed to you
1367 
1368## Best practices
1369 
13701. **Error Handling**
1371 * Leverage Kotlin's type system to model errors explicitly
1372 * Wrap external tool and API calls in `try-catch` blocks when exceptions are possible
1373 * Provide clear and meaningful error messages
1374 * Handle network timeouts and connection issues gracefully
1375 
13762. **Security**
1377 * Store API keys and secrets securely in `local.properties`, environment variables, or secret managers
1378 * Validate all external responses to avoid unexpected or unsafe data usage
1379 * Be cautious with permissions and trust boundaries when using tools
1380 
13813. **Environment**
1382 * Set `ANTHROPIC_API_KEY` through environment variables rather than hardcoding
1383 * Use `.env` files with appropriate `.gitignore` rules for local development
1384 
1385## Troubleshooting
1386 
1387### Server Path Issues
1388 
1389* Double-check the path to your server script is correct
1390* Use the absolute path if the relative path isn't working
1391* For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
1392* Make sure that the required runtime is installed (java for Java, npm for Node.js, or uv for Python)
1393* Verify the server file has the correct extension (.jar for Java, .js for Node.js or .py for Python)
1394 
1395Example of correct path usage:
1396 
1397```bash theme={null}
1398# Relative path
1399java -jar build/libs/client.jar ./server/build/libs/server.jar
1400 
1401# Absolute path
1402java -jar build/libs/client.jar /Users/username/projects/mcp-server/build/libs/server.jar
1403 
1404# Windows path (either format works)
1405java -jar build/libs/client.jar C:/projects/mcp-server/build/libs/server.jar
1406java -jar build/libs/client.jar C:\\projects\\mcp-server\\build\\libs\\server.jar
1407```
1408 
1409### Build Issues
1410 
1411* Use `./gradlew build` or `./gradlew shadowJar` (not `./gradlew jar`) to create the shadow JAR with all dependencies
1412* If you get JDK version errors, ensure your installed JDK version matches or exceeds the `jvmToolchain` setting in `build.gradle.kts`
1413 
1414### Response Timing
1415 
1416* The first response might take up to 30 seconds to return
1417* This is normal and happens while:
1418 * The server initializes
1419 * Claude processes the query
1420 * Tools are being executed
1421* Subsequent responses are typically faster
1422* Don't interrupt the process during this initial waiting period
1423 
1424### Common Error Messages
1425 
1426If you see:
1427 
1428* `Connection refused`: Ensure the server is running and the path is correct
1429* `Tool execution failed`: Verify the tool's required environment variables are set
1430* `ANTHROPIC_API_KEY is not set`: Check your environment variables
1431 
1432**C#**
1433 
1434[You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/csharp-sdk/tree/main/samples/QuickstartClient)
1435 
1436## System Requirements
1437 
1438Before starting, ensure your system meets these requirements:
1439 
1440* .NET 8.0 or higher
1441* Anthropic API key (Claude)
1442* Windows, Linux, or macOS
1443 
1444## Setting up your environment
1445 
1446First, create a new .NET project:
1447 
1448```bash theme={null}
1449dotnet new console -n QuickstartClient
1450cd QuickstartClient
1451```
1452 
1453Then, add the required dependencies to your project:
1454 
1455```bash theme={null}
1456dotnet add package ModelContextProtocol --prerelease
1457dotnet add package Anthropic.SDK
1458dotnet add package Microsoft.Extensions.Hosting
1459dotnet add package Microsoft.Extensions.AI
1460```
1461 
1462## Setting up your API key
1463 
1464You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
1465 
1466```bash theme={null}
1467dotnet user-secrets init
1468dotnet user-secrets set "ANTHROPIC_API_KEY" "<your key here>"
1469```
1470 
1471## Creating the Client
1472 
1473### Basic Client Structure
1474 
1475First, let's setup the basic client class in the file `Program.cs`:
1476 
1477```csharp theme={null}
1478using Anthropic.SDK;
1479using Microsoft.Extensions.AI;
1480using Microsoft.Extensions.Configuration;
1481using Microsoft.Extensions.Hosting;
1482using ModelContextProtocol.Client;
1483using ModelContextProtocol.Protocol.Transport;
1484 
1485var builder = Host.CreateApplicationBuilder(args);
1486 
1487builder.Configuration
1488 .AddEnvironmentVariables()
1489 .AddUserSecrets<Program>();
1490```
1491 
1492This creates the beginnings of a .NET console application that can read the API key from user secrets.
1493 
1494Next, we'll setup the MCP Client:
1495 
1496```csharp theme={null}
1497var (command, arguments) = GetCommandAndArguments(args);
1498 
1499var clientTransport = new StdioClientTransport(new()
1500{
1501 Name = "Demo Server",
1502 Command = command,
1503 Arguments = arguments,
1504});
1505 
1506await using var mcpClient = await McpClient.CreateAsync(clientTransport);
1507 
1508var tools = await mcpClient.ListToolsAsync();
1509foreach (var tool in tools)
1510{
1511 Console.WriteLine($"Connected to server with tools: {tool.Name}");
1512}
1513```
1514 
1515Add this function at the end of the `Program.cs` file:
1516 
1517```csharp theme={null}
1518static (string command, string[] arguments) GetCommandAndArguments(string[] args)
1519{
1520 return args switch
15081521 {
1509 Name = "Demo Server",
1510 Command = command,
1511 Arguments = arguments,
1512 });
1513 
1514 await using var mcpClient = await McpClient.CreateAsync(clientTransport);
1515 
1516 var tools = await mcpClient.ListToolsAsync();
1517 foreach (var tool in tools)
1522 [var script] when script.EndsWith(".py") => ("python", args),
1523 [var script] when script.EndsWith(".js") => ("node", args),
1524 [var script] when Directory.Exists(script) || (File.Exists(script) && script.EndsWith(".csproj")) => ("dotnet", ["run", "--project", script, "--no-build"]),
1525 _ => throw new NotSupportedException("An unsupported server script was provided. Supported scripts are .py, .js, or .csproj")
1526 };
1527}
1528```
1529 
1530This creates an MCP client that will connect to a server that is provided as a command line argument. It then lists the available tools from the connected server.
1531 
1532### Query processing logic
1533 
1534Now let's add the core functionality for processing queries and handling tool calls:
1535 
1536```csharp theme={null}
1537using var anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration["ANTHROPIC_API_KEY"]))
1538 .Messages
1539 .AsBuilder()
1540 .UseFunctionInvocation()
1541 .Build();
1542 
1543var options = new ChatOptions
1544{
1545 MaxOutputTokens = 1000,
1546 ModelId = "claude-opus-5",
1547 Tools = [.. tools]
1548};
1549 
1550Console.ForegroundColor = ConsoleColor.Green;
1551Console.WriteLine("MCP Client Started!");
1552Console.ResetColor();
1553 
1554PromptForInput();
1555while(Console.ReadLine() is string query && !"exit".Equals(query, StringComparison.OrdinalIgnoreCase))
1556{
1557 if (string.IsNullOrWhiteSpace(query))
15181558 {
1519 Console.WriteLine($"Connected to server with tools: {tool.Name}");
1559 PromptForInput();
1560 continue;
15201561 }
1521 ```
1522 
1523 Add this function at the end of the `Program.cs` file:
1524 
1525 ```csharp theme={null}
1526 static (string command, string[] arguments) GetCommandAndArguments(string[] args)
1562 
1563 await foreach (var message in anthropicClient.GetStreamingResponseAsync(query, options))
15271564 {
1528 return args switch
1529 {
1530 [var script] when script.EndsWith(".py") => ("python", args),
1531 [var script] when script.EndsWith(".js") => ("node", args),
1532 [var script] when Directory.Exists(script) || (File.Exists(script) && script.EndsWith(".csproj")) => ("dotnet", ["run", "--project", script, "--no-build"]),
1533 _ => throw new NotSupportedException("An unsupported server script was provided. Supported scripts are .py, .js, or .csproj")
1534 };
1565 Console.Write(message);
15351566 }
1536 ```
1537 
1538 This creates an MCP client that will connect to a server that is provided as a command line argument. It then lists the available tools from the connected server.
1539 
1540 ### Query processing logic
1541 
1542 Now let's add the core functionality for processing queries and handling tool calls:
1543 
1544 ```csharp theme={null}
1545 using var anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration["ANTHROPIC_API_KEY"]))
1546 .Messages
1547 .AsBuilder()
1548 .UseFunctionInvocation()
1549 .Build();
1550 
1551 var options = new ChatOptions
1552 {
1553 MaxOutputTokens = 1000,
1554 ModelId = "claude-opus-5",
1555 Tools = [.. tools]
1556 };
1557 
1558 Console.ForegroundColor = ConsoleColor.Green;
1559 Console.WriteLine("MCP Client Started!");
1567 Console.WriteLine();
1568 
1569 PromptForInput();
1570}
1571 
1572static void PromptForInput()
1573{
1574 Console.WriteLine("Enter a command (or 'exit' to quit):");
1575 Console.ForegroundColor = ConsoleColor.Cyan;
1576 Console.Write("> ");
15601577 Console.ResetColor();
1561 
1562 PromptForInput();
1563 while(Console.ReadLine() is string query && !"exit".Equals(query, StringComparison.OrdinalIgnoreCase))
1564 {
1565 if (string.IsNullOrWhiteSpace(query))
1566 {
1567 PromptForInput();
1568 continue;
1569 }
1570 
1571 await foreach (var message in anthropicClient.GetStreamingResponseAsync(query, options))
1572 {
1573 Console.Write(message);
1574 }
1575 Console.WriteLine();
1576 
1577 PromptForInput();
1578 }
1579 
1580 static void PromptForInput()
1581 {
1582 Console.WriteLine("Enter a command (or 'exit' to quit):");
1583 Console.ForegroundColor = ConsoleColor.Cyan;
1584 Console.Write("> ");
1585 Console.ResetColor();
1586 }
1587 ```
1588 
1589 ## Key Components Explained
1590 
1591 ### 1. Client Initialization
1592 
1593 * The client is initialized using `McpClient.CreateAsync()`, which sets up the transport type and command to run the server.
1594 
1595 ### 2. Server Connection
1596 
1597 * Supports Python, Node.js, and .NET servers.
1598 * The server is started using the command specified in the arguments.
1599 * Configures to use stdio for communication with the server.
1600 * Initializes the session and available tools.
1601 
1602 ### 3. Query Processing
1603 
1604 * Leverages [Microsoft.Extensions.AI](https://learn.microsoft.com/dotnet/ai/ai-extensions) for the chat client.
1605 * Configures the `IChatClient` to use automatic tool (function) invocation.
1606 * The client reads user input and sends it to the server.
1607 * The server processes the query and returns a response.
1608 * The response is displayed to the user.
1609 
1610 ## Running the Client
1611 
1612 To run your client with any MCP server:
1613 
1614 ```bash theme={null}
1615 dotnet run -- path/to/server.csproj # dotnet server
1616 dotnet run -- path/to/server.py # python server
1617 dotnet run -- path/to/server.js # node server
1618 ```
1619 
1620 <Note>
1621 If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `dotnet run -- path/to/QuickstartWeatherServer`.
1622 </Note>
1623 
1624 The client will:
1625 
1626 1. Connect to the specified server
1627 2. List available tools
1628 3. Start an interactive chat session where you can:
1629 * Enter queries
1630 * See tool executions
1631 * Get responses from Claude
1632 4. Exit the session when done
1633 
1634 Here's an example of what it should look like if connected to the weather server quickstart:
1635 
1636 <Frame>
1637 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-dotnet-client.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=fcf28dde150d6db879402ad8150c6b23" width="1115" height="666" data-path="images/quickstart-dotnet-client.png" />
1638 </Frame>
1639 </Tab>
1640 
1641 <Tab title="Ruby">
1642 [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-ruby)
1643 
1644 ## System Requirements
1645 
1646 Before starting, ensure your system meets these requirements:
1647 
1648 * Mac or Windows computer
1649 * Ruby 3.2.0 or higher installed (required by the [Anthropic SDK](https://github.com/anthropics/anthropic-sdk-ruby))
1650 * Anthropic API key (Claude)
1651 
1652 ## Setting Up Your Environment
1653 
1654 First, create a new Ruby project:
1655 
1656 <CodeGroup>
1657 ```bash macOS/Linux theme={null}
1658 # Create project directory
1659 mkdir mcp-client
1660 cd mcp-client
1661 
1662 # Create a Gemfile
1663 bundle init
1664 
1665 # Add required dependencies
1666 bundle add anthropic base64 dotenv mcp
1667 
1668 # Create our main file
1669 touch client.rb
1670 ```
1671 
1672 ```powershell Windows theme={null}
1673 # Create project directory
1674 mkdir mcp-client
1675 cd mcp-client
1676 
1677 # Create a Gemfile
1678 bundle init
1679 
1680 # Add required dependencies
1681 bundle add anthropic base64 dotenv mcp
1682 
1683 # Create our main file
1684 new-item client.rb
1685 ```
1686 </CodeGroup>
1687 
1688 ## Setting Up Your API Key
1689 
1690 You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
1691 
1692 Create a `.env` file to store it:
1693 
1694 ```bash theme={null}
1695 echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env
1696 ```
1697 
1698 Add `.env` to your `.gitignore`:
1699 
1700 ```bash theme={null}
1701 echo ".env" >> .gitignore
1702 ```
1703 
1704 <Warning>
1705 Make sure you keep your `ANTHROPIC_API_KEY` secure!
1706 </Warning>
1707 
1708 ## Creating the Client
1709 
1710 ### Basic Client Structure
1711 
1712 First, let's set up our requires and create the basic client class:
1713 
1714 ```ruby theme={null}
1715 require "anthropic"
1716 require "dotenv/load"
1717 require "json"
1718 require "mcp"
1719 
1720 class MCPClient
1721 ANTHROPIC_MODEL = "claude-opus-5"
1722 
1723 def initialize
1724 @mcp_client = nil
1725 @transport = nil
1726 @anthropic_client = nil
1727 end
1728 
1729 # methods will go here
1730 end
1731 ```
1732 
1733 ### Server Connection Management
1734 
1735 Next, we'll implement the method to connect to an MCP server:
1736 
1737 ```ruby theme={null}
1738 def connect_to_server(server_script_path)
1739 command = case File.extname(server_script_path)
1740 when ".rb"
1741 "ruby"
1742 when ".py"
1743 "python3"
1744 when ".js"
1745 "node"
1746 else
1747 raise ArgumentError, "Server script must be a .rb, .py, or .js file."
1748 end
1749 
1750 @transport = MCP::Client::Stdio.new(command: command, args: [server_script_path])
1751 @mcp_client = MCP::Client.new(transport: @transport)
1752 @mcp_client.connect
1753 
1754 tool_names = @mcp_client.tools.map(&:name)
1755 puts "\nConnected to server with tools: #{tool_names}"
1756 end
1757 ```
1758 
1759 ### Query Processing Logic
1760 
1761 Now let's add the core functionality for processing queries and handling tool calls:
1762 
1763 ```ruby theme={null}
1764 private
1765 
1766 def process_query(query)
1767 messages = [{ role: "user", content: query }]
1768 
1769 available_tools = @mcp_client.tools.map do |tool|
1770 { name: tool.name, description: tool.description, input_schema: tool.input_schema }
1771 end
1772 
1773 # Initial Claude API call.
1774 response = chat(messages, tools: available_tools)
1775 
1776 # Process response and handle tool calls.
1777 if response.content.any?(Anthropic::Models::ToolUseBlock)
1778 assistant_content = response.content.filter_map do |content_block|
1779 case content_block
1780 when Anthropic::Models::TextBlock
1781 { type: "text", text: content_block.text }
1782 when Anthropic::Models::ToolUseBlock
1783 { type: "tool_use", id: content_block.id, name: content_block.name, input: content_block.input }
1784 end
1785 end
1786 messages << { role: "assistant", content: assistant_content }
1787 end
1788 
1789 response.content.each_with_object([]) do |content, response_parts|
1790 case content
1791 when Anthropic::Models::TextBlock
1792 response_parts << content.text
1793 when Anthropic::Models::ToolUseBlock
1794 # Execute tool call via MCP.
1795 result = @mcp_client.call_tool(name: content.name, arguments: content.input)
1796 response_parts << "[Calling tool #{content.name} with args #{content.input.to_json}]"
1797 
1798 tool_result_content = result.dig("result", "content")
1799 result_text = if tool_result_content.is_a?(Array)
1800 tool_result_content.filter_map { |content_item| content_item["text"] }.join("\n")
1801 else
1802 tool_result_content.to_s
1803 end
1804 
1805 messages << {
1806 role: "user",
1807 content: [{
1808 type: "tool_result",
1809 tool_use_id: content.id,
1810 content: result_text
1811 }]
1812 }
1813 
1814 # Get next response from Claude.
1815 response = chat(messages)
1816 
1817 response.content.each do |content_block|
1818 response_parts << content_block.text if content_block.is_a?(Anthropic::Models::TextBlock)
1819 end
1820 end
1821 end.join("\n")
1822 end
1823 
1824 def chat(messages, tools: nil)
1825 params = { model: ANTHROPIC_MODEL, max_tokens: 1000, messages: messages }
1826 params[:tools] = tools if tools
1827 
1828 anthropic_client.messages.create(**params)
1829 end
1830 
1831 def anthropic_client
1832 @anthropic_client ||= Anthropic::Client.new(api_key: ENV["ANTHROPIC_API_KEY"])
1833 end
1834 ```
1835 
1836 ### Interactive Chat Interface
1837 
1838 Now we'll add the chat loop and cleanup functionality:
1839 
1840 ```ruby theme={null}
1841 def chat_loop
1842 puts <<~MESSAGE
1843 MCP Client Started!
1844 Type your queries or 'quit' to exit.
1845 MESSAGE
1846 
1847 loop do
1848 print "\nQuery: "
1849 line = $stdin.gets
1850 break if line.nil?
1851 
1852 query = line.chomp.strip
1853 break if query.downcase == "quit"
1854 next if query.empty?
1855 
1856 begin
1857 response = process_query(query)
1858 puts "\n#{response}"
1859 rescue => e
1860 puts "\nError: #{e.message}"
1861 end
1578}
1579```
1580 
1581## Key Components Explained
1582 
1583### 1. Client Initialization
1584 
1585* The client is initialized using `McpClient.CreateAsync()`, which sets up the transport type and command to run the server.
1586 
1587### 2. Server Connection
1588 
1589* Supports Python, Node.js, and .NET servers.
1590* The server is started using the command specified in the arguments.
1591* Configures to use stdio for communication with the server.
1592* Initializes the session and available tools.
1593 
1594### 3. Query Processing
1595 
1596* Leverages [Microsoft.Extensions.AI](https://learn.microsoft.com/dotnet/ai/ai-extensions) for the chat client.
1597* Configures the `IChatClient` to use automatic tool (function) invocation.
1598* The client reads user input and sends it to the server.
1599* The server processes the query and returns a response.
1600* The response is displayed to the user.
1601 
1602## Running the Client
1603 
1604To run your client with any MCP server:
1605 
1606```bash theme={null}
1607dotnet run -- path/to/server.csproj # dotnet server
1608dotnet run -- path/to/server.py # python server
1609dotnet run -- path/to/server.js # node server
1610```
1611 
1612> [!NOTE]
1613>
1614> If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `dotnet run -- path/to/QuickstartWeatherServer`.
1615 
1616The client will:
1617 
16181. Connect to the specified server
16192. List available tools
16203. Start an interactive chat session where you can:
1621 * Enter queries
1622 * See tool executions
1623 * Get responses from Claude
16244. Exit the session when done
1625 
1626Here's an example of what it should look like if connected to the weather server quickstart:
1627 
1628![](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-dotnet-client.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=fcf28dde150d6db879402ad8150c6b23)
1629 
1630**Ruby**
1631 
1632[You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-ruby)
1633 
1634## System Requirements
1635 
1636Before starting, ensure your system meets these requirements:
1637 
1638* Mac or Windows computer
1639* Ruby 3.2.0 or higher installed (required by the [Anthropic SDK](https://github.com/anthropics/anthropic-sdk-ruby))
1640* Anthropic API key (Claude)
1641 
1642## Setting Up Your Environment
1643 
1644First, create a new Ruby project:
1645 
1646```bash macOS/Linux theme={null}
1647# Create project directory
1648mkdir mcp-client
1649cd mcp-client
1650 
1651# Create a Gemfile
1652bundle init
1653 
1654# Add required dependencies
1655bundle add anthropic base64 dotenv mcp
1656 
1657# Create our main file
1658touch client.rb
1659```
1660 
1661```powershell Windows theme={null}
1662# Create project directory
1663mkdir mcp-client
1664cd mcp-client
1665 
1666# Create a Gemfile
1667bundle init
1668 
1669# Add required dependencies
1670bundle add anthropic base64 dotenv mcp
1671 
1672# Create our main file
1673new-item client.rb
1674```
1675 
1676## Setting Up Your API Key
1677 
1678You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
1679 
1680Create a `.env` file to store it:
1681 
1682```bash theme={null}
1683echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env
1684```
1685 
1686Add `.env` to your `.gitignore`:
1687 
1688```bash theme={null}
1689echo ".env" >> .gitignore
1690```
1691 
1692> [!WARNING]
1693>
1694> Make sure you keep your `ANTHROPIC_API_KEY` secure!
1695 
1696## Creating the Client
1697 
1698### Basic Client Structure
1699 
1700First, let's set up our requires and create the basic client class:
1701 
1702```ruby theme={null}
1703require "anthropic"
1704require "dotenv/load"
1705require "json"
1706require "mcp"
1707 
1708class MCPClient
1709 ANTHROPIC_MODEL = "claude-opus-5"
1710 
1711 def initialize
1712 @mcp_client = nil
1713 @transport = nil
1714 @anthropic_client = nil
1715 end
1716 
1717 # methods will go here
1718end
1719```
1720 
1721### Server Connection Management
1722 
1723Next, we'll implement the method to connect to an MCP server:
1724 
1725```ruby theme={null}
1726def connect_to_server(server_script_path)
1727 command = case File.extname(server_script_path)
1728 when ".rb"
1729 "ruby"
1730 when ".py"
1731 "python3"
1732 when ".js"
1733 "node"
1734 else
1735 raise ArgumentError, "Server script must be a .rb, .py, or .js file."
1736 end
1737 
1738 @transport = MCP::Client::Stdio.new(command: command, args: [server_script_path])
1739 @mcp_client = MCP::Client.new(transport: @transport)
1740 @mcp_client.connect
1741 
1742 tool_names = @mcp_client.tools.map(&:name)
1743 puts "\nConnected to server with tools: #{tool_names}"
1744end
1745```
1746 
1747### Query Processing Logic
1748 
1749Now let's add the core functionality for processing queries and handling tool calls:
1750 
1751```ruby theme={null}
1752private
1753 
1754def process_query(query)
1755 messages = [{ role: "user", content: query }]
1756 
1757 available_tools = @mcp_client.tools.map do |tool|
1758 { name: tool.name, description: tool.description, input_schema: tool.input_schema }
1759 end
1760 
1761 # Initial Claude API call.
1762 response = chat(messages, tools: available_tools)
1763 
1764 # Process response and handle tool calls.
1765 if response.content.any?(Anthropic::Models::ToolUseBlock)
1766 assistant_content = response.content.filter_map do |content_block|
1767 case content_block
1768 when Anthropic::Models::TextBlock
1769 { type: "text", text: content_block.text }
1770 when Anthropic::Models::ToolUseBlock
1771 { type: "tool_use", id: content_block.id, name: content_block.name, input: content_block.input }
18621772 end
18631773 end
1864 
1865 def cleanup
1866 @transport&.close
1774 messages << { role: "assistant", content: assistant_content }
1775 end
1776 
1777 response.content.each_with_object([]) do |content, response_parts|
1778 case content
1779 when Anthropic::Models::TextBlock
1780 response_parts << content.text
1781 when Anthropic::Models::ToolUseBlock
1782 # Execute tool call via MCP.
1783 result = @mcp_client.call_tool(name: content.name, arguments: content.input)
1784 response_parts << "[Calling tool #{content.name} with args #{content.input.to_json}]"
1785 
1786 tool_result_content = result.dig("result", "content")
1787 result_text = if tool_result_content.is_a?(Array)
1788 tool_result_content.filter_map { |content_item| content_item["text"] }.join("\n")
1789 else
1790 tool_result_content.to_s
1791 end
1792 
1793 messages << {
1794 role: "user",
1795 content: [{
1796 type: "tool_result",
1797 tool_use_id: content.id,
1798 content: result_text
1799 }]
1800 }
1801 
1802 # Get next response from Claude.
1803 response = chat(messages)
1804 
1805 response.content.each do |content_block|
1806 response_parts << content_block.text if content_block.is_a?(Anthropic::Models::TextBlock)
1807 end
18671808 end
1868 ```
1869 
1870 ### Main Entry Point
1871 
1872 Finally, we'll add the main execution logic:
1873 
1874 ```ruby theme={null}
1875 if ARGV.empty?
1876 puts "Usage: ruby client.rb <path_to_server_script>"
1877 exit 1
1809 end.join("\n")
1810end
1811 
1812def chat(messages, tools: nil)
1813 params = { model: ANTHROPIC_MODEL, max_tokens: 1000, messages: messages }
1814 params[:tools] = tools if tools
1815 
1816 anthropic_client.messages.create(**params)
1817end
1818 
1819def anthropic_client
1820 @anthropic_client ||= Anthropic::Client.new(api_key: ENV["ANTHROPIC_API_KEY"])
1821end
1822```
1823 
1824### Interactive Chat Interface
1825 
1826Now we'll add the chat loop and cleanup functionality:
1827 
1828```ruby theme={null}
1829def chat_loop
1830 puts <<~MESSAGE
1831 MCP Client Started!
1832 Type your queries or 'quit' to exit.
1833 MESSAGE
1834 
1835 loop do
1836 print "\nQuery: "
1837 line = $stdin.gets
1838 break if line.nil?
1839 
1840 query = line.chomp.strip
1841 break if query.downcase == "quit"
1842 next if query.empty?
1843 
1844 begin
1845 response = process_query(query)
1846 puts "\n#{response}"
1847 rescue => e
1848 puts "\nError: #{e.message}"
18781849 end
1879 
1880 client = MCPClient.new
1881 
1882 begin
1883 client.connect_to_server(ARGV[0])
1884 
1885 api_key = ENV["ANTHROPIC_API_KEY"]
1886 if api_key.nil? || api_key.empty?
1887 puts <<~MESSAGE
1888 No ANTHROPIC_API_KEY found. To query these tools with Claude, set your API key:
1889 export ANTHROPIC_API_KEY=your-api-key-here
1890 MESSAGE
1891 exit
1892 end
1893 
1894 client.chat_loop
1895 rescue => e
1896 puts "Error: #{e.message}"
1897 exit 1
1898 ensure
1899 client.cleanup
1900 end
1901 ```
1902 
1903 You can find the complete `client.rb` file [here](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-ruby/client.rb).
1904 
1905 ## Key Components Explained
1906 
1907 ### 1. Client Initialization
1908 
1909 * The `MCPClient` class initializes with nil references for lazy setup
1910 * The Anthropic client is lazily initialized via the `anthropic_client` method
1911 * Uses `dotenv` to load environment variables from `.env`
1912 
1913 ### 2. Server Connection
1914 
1915 * Supports Ruby, Python, and Node.js servers
1916 * Uses `File.extname` to determine the server script type
1917 * Uses `MCP::Client::Stdio` for stdio transport
1918 * Initializes the MCP client and lists available tools
1919 
1920 ### 3. Query Processing
1921 
1922 * Maps MCP tools to Anthropic tool format (`name`, `description`, `input_schema`)
1923 * Uses `Anthropic::Models::TextBlock` and `Anthropic::Models::ToolUseBlock` for pattern matching
1924 * Builds assistant content once before iterating tool calls
1925 * Executes tool calls via `@mcp_client.call_tool`
1926 * Uses `chat` helper method to wrap Anthropic API calls
1927 * Extracts tool result content with `result.dig("result", "content")`
1928 * Passes tool results back to Claude for a final response
1929 
1930 ### 4. Interactive Interface
1931 
1932 * Provides a simple command-line interface
1933 * Handles user input and displays responses
1934 * Skips empty queries
1935 * Includes basic error handling
1936 
1937 ### 5. Resource Management
1938 
1939 * Proper cleanup of the transport via `begin`...`ensure`
1940 * Top-level `rescue` for error handling
1941 * API key validation after server connection
1942 
1943 ## Running the Client
1944 
1945 To run your client with any MCP server:
1946 
1947 ```bash theme={null}
1948 bundle exec ruby client.rb path/to/server.rb # ruby server
1949 bundle exec ruby client.rb path/to/server.py # python server
1950 bundle exec ruby client.rb path/to/build/index.js # node server
1951 ```
1952 
1953 <Note>
1954 If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-ruby), your command might look something like this: `bundle exec ruby client.rb /path/to/weather-server-ruby/weather.rb`
1955 </Note>
1956 
1957 The client will:
1958 
1959 1. Connect to the specified server
1960 2. List available tools
1961 3. Start an interactive chat session where you can:
1962 * Enter queries
1963 * See tool executions
1964 * Get responses from Claude
1965 
1966 ## How It Works
1967 
1968 When you submit a query:
1969 
1970 1. The client gets the list of available tools from the server
1971 2. Your query is sent to Claude along with tool descriptions
1972 3. Claude decides which tools (if any) to use
1973 4. The client executes any requested tool calls through the server
1974 5. Results are sent back to Claude
1975 6. Claude provides a natural language response
1976 7. The response is displayed to you
1977 
1978 ## Best practices
1979 
1980 1. **Error Handling**
1981 * Wrap tool calls in `begin`...`rescue` blocks
1982 * Provide meaningful error messages
1983 * Gracefully handle connection issues
1984 
1985 2. **Resource Management**
1986 * Always close the transport when done
1987 * Use `begin`...`ensure` for proper cleanup
1988 * Handle server disconnections
1989 
1990 3. **Security**
1991 * Store API keys securely in `.env`
1992 * Validate server responses
1993 * Be cautious with tool permissions
1994 
1995 4. **Tool Names**
1996 * Tool names can be validated according to the format specified [here](/specification/2026-07-28/server/tools#tool-names)
1997 * If a tool name conforms to the specified format, it should not fail validation by an MCP client
1998 
1999 ## Troubleshooting
2000 
2001 ### Server Path Issues
2002 
2003 * Double-check the path to your server script is correct
2004 * Use the absolute path if the relative path isn't working
2005 * For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
2006 * Verify the server file has the correct extension (.py for Python, .js for Node.js, or .rb for Ruby)
2007 
2008 Example of correct path usage:
2009 
2010 ```bash theme={null}
2011 # Relative path
2012 bundle exec ruby client.rb ./server/weather.rb
2013 
2014 # Absolute path
2015 bundle exec ruby client.rb /Users/username/projects/mcp-server/weather.rb
2016 
2017 # Windows path (either format works)
2018 bundle exec ruby client.rb C:/projects/mcp-server/weather.rb
2019 bundle exec ruby client.rb C:\\projects\\mcp-server\\weather.rb
2020 ```
2021 
2022 ### Response Timing
2023 
2024 * The first response might take up to 30 seconds to return
2025 * This is normal and happens while:
2026 * The server initializes
2027 * Claude processes the query
2028 * Tools are being executed
2029 * Subsequent responses are typically faster
2030 * Don't interrupt the process during this initial waiting period
2031 
2032 ### Common Error Messages
2033 
2034 If you see:
2035 
2036 * `Errno::ENOENT`: Check your server path and ensure the command (`ruby`, `python3`, `node`) is available
2037 * `Connection refused`: Ensure the server is running and the path is correct
2038 * `Tool execution failed`: Verify the tool's required environment variables are set
2039 * `Anthropic::Errors::AuthenticationError`: Check your `.env` file has a valid `ANTHROPIC_API_KEY`
2040 </Tab>
2041 
2042 <Tab title="Rust">
2043 [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-rust)
2044 
2045 ## System Requirements
2046 
2047 Before starting, ensure your Linux system meets these requirements:
2048 
2049 * Latest stable version of [Rust and Cargo](https://www.rust-lang.org/tools/install)
2050 * Anthropic API key (Claude)
2051 * A Python, Node.js, or executable MCP server to connect to
2052 
2053 ## Setting Up Your Environment
2054 
2055 First, create a new Rust project:
2056 
2057 ```bash theme={null}
2058 cargo new mcp-client-rust
2059 cd mcp-client-rust
2060 ```
2061 
2062 Replace the contents of `Cargo.toml` with the following:
2063 
2064 ```toml Cargo.toml theme={null}
2065 [package]
2066 name = "mcp-client-rust"
2067 version = "0.1.0"
2068 edition = "2024"
2069 
2070 [dependencies]
2071 anyhow = "1.0.100"
2072 genai = "0.4.2"
2073 rmcp = { version = "0.8.0", features = ["server", "client", "transport-io", "transport-child-process"] }
2074 tokio = { version = "1.47.1", features = ["full"] }
2075 tracing = "0.1.41"
2076 tracing-subscriber = { version = "0.3", features = ["env-filter"] }
2077 serde_json = "1.0.128"
2078 dotenvy = "0.15.7"
2079 reqwest = "0.12.23"
2080 ```
2081 
2082 The [`rmcp`](https://github.com/modelcontextprotocol/rust-sdk) crate provides the Rust MCP SDK and child-process transport. This example uses the [`genai`](https://github.com/jeremychone/rust-genai) crate to send requests to Claude and represent tools in the model request.
2083 
2084 ## Setting Up Your API Key
2085 
2086 You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
2087 
2088 Create a `.env` file to store it:
2089 
2090 ```bash theme={null}
2091 echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env
2092 ```
2093 
2094 Add `.env` to your `.gitignore`:
2095 
2096 ```bash theme={null}
2097 echo ".env" >> .gitignore
2098 ```
2099 
2100 <Warning>
2101 Make sure you keep your `ANTHROPIC_API_KEY` secure!
2102 </Warning>
2103 
2104 ## Creating the Client
2105 
2106 Open `src/main.rs` and replace its contents as you work through the following sections.
2107 
2108 ### Imports and Client Structure
2109 
2110 First, add the imports, model constant, and basic client structure:
2111 
2112 ```rust theme={null}
2113 use anyhow::{Context, Result, bail};
2114 use genai::Client;
2115 use genai::chat::{
2116 ChatMessage, ChatRequest, ChatResponse, ContentPart, Tool as GenaiTool, ToolResponse,
2117 };
2118 use rmcp::model::{CallToolRequestParam, Tool as McpTool};
2119 use rmcp::service::{RoleClient, RunningService, ServiceExt};
2120 use rmcp::transport::TokioChildProcess;
2121 use serde_json::Value;
2122 use tokio::io::{self, AsyncBufReadExt, BufReader};
2123 use tokio::process::Command;
2124 
2125 const MODEL_ANTHROPIC: &str = "claude-opus-5";
2126 
2127 struct MCPClient {
2128 anthropic: Client,
2129 session: Option<RunningService<RoleClient, ()>>,
2130 tools: Vec<GenaiTool>,
1850 end
1851end
1852 
1853def cleanup
1854 @transport&.close
1855end
1856```
1857 
1858### Main Entry Point
1859 
1860Finally, we'll add the main execution logic:
1861 
1862```ruby theme={null}
1863if ARGV.empty?
1864 puts "Usage: ruby client.rb <path_to_server_script>"
1865 exit 1
1866end
1867 
1868client = MCPClient.new
1869 
1870begin
1871 client.connect_to_server(ARGV[0])
1872 
1873 api_key = ENV["ANTHROPIC_API_KEY"]
1874 if api_key.nil? || api_key.empty?
1875 puts <<~MESSAGE
1876 No ANTHROPIC_API_KEY found. To query these tools with Claude, set your API key:
1877 export ANTHROPIC_API_KEY=your-api-key-here
1878 MESSAGE
1879 exit
1880 end
1881 
1882 client.chat_loop
1883rescue => e
1884 puts "Error: #{e.message}"
1885 exit 1
1886ensure
1887 client.cleanup
1888end
1889```
1890 
1891You can find the complete `client.rb` file [here](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-ruby/client.rb).
1892 
1893## Key Components Explained
1894 
1895### 1. Client Initialization
1896 
1897* The `MCPClient` class initializes with nil references for lazy setup
1898* The Anthropic client is lazily initialized via the `anthropic_client` method
1899* Uses `dotenv` to load environment variables from `.env`
1900 
1901### 2. Server Connection
1902 
1903* Supports Ruby, Python, and Node.js servers
1904* Uses `File.extname` to determine the server script type
1905* Uses `MCP::Client::Stdio` for stdio transport
1906* Initializes the MCP client and lists available tools
1907 
1908### 3. Query Processing
1909 
1910* Maps MCP tools to Anthropic tool format (`name`, `description`, `input_schema`)
1911* Uses `Anthropic::Models::TextBlock` and `Anthropic::Models::ToolUseBlock` for pattern matching
1912* Builds assistant content once before iterating tool calls
1913* Executes tool calls via `@mcp_client.call_tool`
1914* Uses `chat` helper method to wrap Anthropic API calls
1915* Extracts tool result content with `result.dig("result", "content")`
1916* Passes tool results back to Claude for a final response
1917 
1918### 4. Interactive Interface
1919 
1920* Provides a simple command-line interface
1921* Handles user input and displays responses
1922* Skips empty queries
1923* Includes basic error handling
1924 
1925### 5. Resource Management
1926 
1927* Proper cleanup of the transport via `begin`...`ensure`
1928* Top-level `rescue` for error handling
1929* API key validation after server connection
1930 
1931## Running the Client
1932 
1933To run your client with any MCP server:
1934 
1935```bash theme={null}
1936bundle exec ruby client.rb path/to/server.rb # ruby server
1937bundle exec ruby client.rb path/to/server.py # python server
1938bundle exec ruby client.rb path/to/build/index.js # node server
1939```
1940 
1941> [!NOTE]
1942>
1943> If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-ruby), your command might look something like this: `bundle exec ruby client.rb /path/to/weather-server-ruby/weather.rb`
1944 
1945The client will:
1946 
19471. Connect to the specified server
19482. List available tools
19493. Start an interactive chat session where you can:
1950 * Enter queries
1951 * See tool executions
1952 * Get responses from Claude
1953 
1954## How It Works
1955 
1956When you submit a query:
1957 
19581. The client gets the list of available tools from the server
19592. Your query is sent to Claude along with tool descriptions
19603. Claude decides which tools (if any) to use
19614. The client executes any requested tool calls through the server
19625. Results are sent back to Claude
19636. Claude provides a natural language response
19647. The response is displayed to you
1965 
1966## Best practices
1967 
19681. **Error Handling**
1969 * Wrap tool calls in `begin`...`rescue` blocks
1970 * Provide meaningful error messages
1971 * Gracefully handle connection issues
1972 
19732. **Resource Management**
1974 * Always close the transport when done
1975 * Use `begin`...`ensure` for proper cleanup
1976 * Handle server disconnections
1977 
19783. **Security**
1979 * Store API keys securely in `.env`
1980 * Validate server responses
1981 * Be cautious with tool permissions
1982 
19834. **Tool Names**
1984 * Tool names can be validated according to the format specified [here](/specification/2026-07-28/server/tools#tool-names)
1985 * If a tool name conforms to the specified format, it should not fail validation by an MCP client
1986 
1987## Troubleshooting
1988 
1989### Server Path Issues
1990 
1991* Double-check the path to your server script is correct
1992* Use the absolute path if the relative path isn't working
1993* For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
1994* Verify the server file has the correct extension (.py for Python, .js for Node.js, or .rb for Ruby)
1995 
1996Example of correct path usage:
1997 
1998```bash theme={null}
1999# Relative path
2000bundle exec ruby client.rb ./server/weather.rb
2001 
2002# Absolute path
2003bundle exec ruby client.rb /Users/username/projects/mcp-server/weather.rb
2004 
2005# Windows path (either format works)
2006bundle exec ruby client.rb C:/projects/mcp-server/weather.rb
2007bundle exec ruby client.rb C:\\projects\\mcp-server\\weather.rb
2008```
2009 
2010### Response Timing
2011 
2012* The first response might take up to 30 seconds to return
2013* This is normal and happens while:
2014 * The server initializes
2015 * Claude processes the query
2016 * Tools are being executed
2017* Subsequent responses are typically faster
2018* Don't interrupt the process during this initial waiting period
2019 
2020### Common Error Messages
2021 
2022If you see:
2023 
2024* `Errno::ENOENT`: Check your server path and ensure the command (`ruby`, `python3`, `node`) is available
2025* `Connection refused`: Ensure the server is running and the path is correct
2026* `Tool execution failed`: Verify the tool's required environment variables are set
2027* `Anthropic::Errors::AuthenticationError`: Check your `.env` file has a valid `ANTHROPIC_API_KEY`
2028 
2029**Rust**
2030 
2031[You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-rust)
2032 
2033## System Requirements
2034 
2035Before starting, ensure your Linux system meets these requirements:
2036 
2037* Latest stable version of [Rust and Cargo](https://www.rust-lang.org/tools/install)
2038* Anthropic API key (Claude)
2039* A Python, Node.js, or executable MCP server to connect to
2040 
2041## Setting Up Your Environment
2042 
2043First, create a new Rust project:
2044 
2045```bash theme={null}
2046cargo new mcp-client-rust
2047cd mcp-client-rust
2048```
2049 
2050Replace the contents of `Cargo.toml` with the following:
2051 
2052```toml Cargo.toml theme={null}
2053[package]
2054name = "mcp-client-rust"
2055version = "0.1.0"
2056edition = "2024"
2057 
2058[dependencies]
2059anyhow = "1.0.100"
2060genai = "0.4.2"
2061rmcp = { version = "0.8.0", features = ["server", "client", "transport-io", "transport-child-process"] }
2062tokio = { version = "1.47.1", features = ["full"] }
2063tracing = "0.1.41"
2064tracing-subscriber = { version = "0.3", features = ["env-filter"] }
2065serde_json = "1.0.128"
2066dotenvy = "0.15.7"
2067reqwest = "0.12.23"
2068```
2069 
2070The [`rmcp`](https://github.com/modelcontextprotocol/rust-sdk) crate provides the Rust MCP SDK and child-process transport. This example uses the [`genai`](https://github.com/jeremychone/rust-genai) crate to send requests to Claude and represent tools in the model request.
2071 
2072## Setting Up Your API Key
2073 
2074You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
2075 
2076Create a `.env` file to store it:
2077 
2078```bash theme={null}
2079echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env
2080```
2081 
2082Add `.env` to your `.gitignore`:
2083 
2084```bash theme={null}
2085echo ".env" >> .gitignore
2086```
2087 
2088> [!WARNING]
2089>
2090> Make sure you keep your `ANTHROPIC_API_KEY` secure!
2091 
2092## Creating the Client
2093 
2094Open `src/main.rs` and replace its contents as you work through the following sections.
2095 
2096### Imports and Client Structure
2097 
2098First, add the imports, model constant, and basic client structure:
2099 
2100```rust theme={null}
2101use anyhow::{Context, Result, bail};
2102use genai::Client;
2103use genai::chat::{
2104 ChatMessage, ChatRequest, ChatResponse, ContentPart, Tool as GenaiTool, ToolResponse,
2105};
2106use rmcp::model::{CallToolRequestParam, Tool as McpTool};
2107use rmcp::service::{RoleClient, RunningService, ServiceExt};
2108use rmcp::transport::TokioChildProcess;
2109use serde_json::Value;
2110use tokio::io::{self, AsyncBufReadExt, BufReader};
2111use tokio::process::Command;
2112 
2113const MODEL_ANTHROPIC: &str = "claude-opus-5";
2114 
2115struct MCPClient {
2116 anthropic: Client,
2117 session: Option<RunningService<RoleClient, ()>>,
2118 tools: Vec<GenaiTool>,
2119}
2120```
2121 
2122The client keeps the model API client, the active MCP session, and the tools advertised by the connected server.
2123 
2124### Client Initialization
2125 
2126Next, initialize the model client and start without an MCP session or tools:
2127 
2128```rust theme={null}
2129impl MCPClient {
2130 fn new() -> Result<Self> {
2131 Ok(MCPClient {
2132 anthropic: Client::default(),
2133 session: None,
2134 tools: Vec::new(),
2135 })
21312136 }
2132 ```
2133 
2134 The client keeps the model API client, the active MCP session, and the tools advertised by the connected server.
2135 
2136 ### Client Initialization
2137 
2138 Next, initialize the model client and start without an MCP session or tools:
2139 
2140 ```rust theme={null}
2141 impl MCPClient {
2142 fn new() -> Result<Self> {
2143 Ok(MCPClient {
2144 anthropic: Client::default(),
2145 session: None,
2146 tools: Vec::new(),
2147 })
2137 
2138 // Additional methods will go here.
2139}
2140```
2141 
2142`genai::Client::default()` reads the `ANTHROPIC_API_KEY` environment variable when it sends a request.
2143 
2144### Server Connection Management
2145 
2146Add this method inside the `impl MCPClient` block:
2147 
2148```rust theme={null}
2149async fn connect_to_server(&mut self, server_args: &[String]) -> Result<()> {
2150 if self.session.is_some() {
2151 bail!("Client is already connected to a server");
2152 }
2153 
2154 let mut command = Command::new(&server_args[0]);
2155 command.args(&server_args[1..]);
2156 
2157 let process = TokioChildProcess::new(command)
2158 .with_context(|| format!("Failed to spawn server process for {:?}", server_args))?;
2159 
2160 let session = ().serve(process).await?;
2161 
2162 let rmcp_tools = session
2163 .list_all_tools()
2164 .await
2165 .context("Unable to list tools from server")?;
2166 
2167 let tool_names: Vec<String> = rmcp_tools
2168 .iter()
2169 .map(|tool| tool.name.to_string())
2170 .collect();
2171 
2172 println!("Connected to server with tools: {tool_names:?}");
2173 
2174 self.tools = convert_tools(&rmcp_tools);
2175 self.session = Some(session);
2176 Ok(())
2177}
2178```
2179 
2180This method:
2181 
21821. Starts the server as a child process using the command and arguments supplied on the command line
21832. Establishes an MCP session over stdio
21843. Lists all tools advertised by the server
21854. Converts those tools into the format used in model requests
2186 
2187### Converting MCP Tools
2188 
2189Add this function outside the `impl MCPClient` block:
2190 
2191```rust theme={null}
2192fn convert_tools(tools: &[McpTool]) -> Vec<GenaiTool> {
2193 tools
2194 .iter()
2195 .map(|tool| GenaiTool {
2196 name: tool.name.to_string(),
2197 description: tool.description.as_deref().map(str::to_string),
2198 schema: Some(Value::Object(tool.input_schema.as_ref().clone())),
2199 config: None,
2200 })
2201 .collect()
2202}
2203```
2204 
2205MCP and model APIs describe tools with similar information but different Rust types. `convert_tools` maps each MCP tool's name, description, and input schema into a `genai` tool definition.
2206 
2207### Sending Model Requests
2208 
2209Add this helper method inside `impl MCPClient`:
2210 
2211```rust theme={null}
2212async fn request_model(&self, chat_req: &ChatRequest) -> Result<ChatResponse> {
2213 let response = self
2214 .anthropic
2215 .exec_chat(MODEL_ANTHROPIC, chat_req.clone(), None)
2216 .await
2217 .context("Anthropic chat request failed")?;
2218 
2219 Ok(response)
2220}
2221```
2222 
2223This keeps model request handling in one place and adds useful context if the API request fails.
2224 
2225### Query Processing Logic
2226 
2227Now add the core query-processing method inside `impl MCPClient`:
2228 
2229```rust theme={null}
2230async fn process_query(&mut self, query: &str) -> Result<String> {
2231 let session = self
2232 .session
2233 .as_ref()
2234 .context("Client is not connected to any server")?;
2235 
2236 let mut messages = vec![ChatMessage::user(query)];
2237 let mut final_text = Vec::new();
2238 
2239 // Initial Claude API call with tools
2240 let mut chat_req = ChatRequest::new(messages.clone()).with_tools(self.tools.clone());
2241 let mut chat_rsp = self.request_model(&chat_req).await?;
2242 
2243 // Process response content - collect text and handle tool calls
2244 for text in chat_rsp.texts() {
2245 final_text.push(text.to_string());
2246 }
2247 
2248 let tool_calls = chat_rsp.tool_calls();
2249 if !tool_calls.is_empty() {
2250 // Append assistant's response to message history
2251 messages.push(ChatMessage::assistant(chat_rsp.content.clone()));
2252 
2253 // Execute each tool call and collect responses
2254 let mut tool_results = Vec::new();
2255 for tool_call in tool_calls {
2256 // Add information about the tool call to final text
2257 let tool_args_str = serde_json::to_string(&tool_call.fn_arguments)
2258 .unwrap_or_else(|_| "{}".to_string());
2259 
2260 final_text.push(format!(
2261 "[Calling tool {} with args {}]",
2262 tool_call.fn_name, tool_args_str
2263 ));
2264 
2265 // Query the MCP server
2266 let tool_result = session
2267 .call_tool(CallToolRequestParam {
2268 name: tool_call.fn_name.clone().into(),
2269 arguments: tool_call.fn_arguments.as_object().cloned(),
2270 })
2271 .await
2272 .with_context(|| format!("Tool call {} failed", tool_call.fn_name))?;
2273 
2274 let payload = serde_json::to_string(&tool_result)
2275 .context("Failed to serialize tool result")?;
2276 
2277 tool_results.push(ContentPart::ToolResponse(ToolResponse::new(
2278 tool_call.call_id.clone(),
2279 payload,
2280 )));
21482281 }
21492282 
2150 // Additional methods will go here.
2151 }
2152 ```
2153 
2154 `genai::Client::default()` reads the `ANTHROPIC_API_KEY` environment variable when it sends a request.
2155 
2156 ### Server Connection Management
2157 
2158 Add this method inside the `impl MCPClient` block:
2159 
2160 ```rust theme={null}
2161 async fn connect_to_server(&mut self, server_args: &[String]) -> Result<()> {
2162 if self.session.is_some() {
2163 bail!("Client is already connected to a server");
2164 }
2165 
2166 let mut command = Command::new(&server_args[0]);
2167 command.args(&server_args[1..]);
2168 
2169 let process = TokioChildProcess::new(command)
2170 .with_context(|| format!("Failed to spawn server process for {:?}", server_args))?;
2171 
2172 let session = ().serve(process).await?;
2173 
2174 let rmcp_tools = session
2175 .list_all_tools()
2176 .await
2177 .context("Unable to list tools from server")?;
2178 
2179 let tool_names: Vec<String> = rmcp_tools
2180 .iter()
2181 .map(|tool| tool.name.to_string())
2182 .collect();
2183 
2184 println!("Connected to server with tools: {tool_names:?}");
2185 
2186 self.tools = convert_tools(&rmcp_tools);
2187 self.session = Some(session);
2188 Ok(())
2189 }
2190 ```
2191 
2192 This method:
2193 
2194 1. Starts the server as a child process using the command and arguments supplied on the command line
2195 2. Establishes an MCP session over stdio
2196 3. Lists all tools advertised by the server
2197 4. Converts those tools into the format used in model requests
2198 
2199 ### Converting MCP Tools
2200 
2201 Add this function outside the `impl MCPClient` block:
2202 
2203 ```rust theme={null}
2204 fn convert_tools(tools: &[McpTool]) -> Vec<GenaiTool> {
2205 tools
2206 .iter()
2207 .map(|tool| GenaiTool {
2208 name: tool.name.to_string(),
2209 description: tool.description.as_deref().map(str::to_string),
2210 schema: Some(Value::Object(tool.input_schema.as_ref().clone())),
2211 config: None,
2212 })
2213 .collect()
2214 }
2215 ```
2216 
2217 MCP and model APIs describe tools with similar information but different Rust types. `convert_tools` maps each MCP tool's name, description, and input schema into a `genai` tool definition.
2218 
2219 ### Sending Model Requests
2220 
2221 Add this helper method inside `impl MCPClient`:
2222 
2223 ```rust theme={null}
2224 async fn request_model(&self, chat_req: &ChatRequest) -> Result<ChatResponse> {
2225 let response = self
2226 .anthropic
2227 .exec_chat(MODEL_ANTHROPIC, chat_req.clone(), None)
2228 .await
2229 .context("Anthropic chat request failed")?;
2230 
2231 Ok(response)
2232 }
2233 ```
2234 
2235 This keeps model request handling in one place and adds useful context if the API request fails.
2236 
2237 ### Query Processing Logic
2238 
2239 Now add the core query-processing method inside `impl MCPClient`:
2240 
2241 ```rust theme={null}
2242 async fn process_query(&mut self, query: &str) -> Result<String> {
2243 let session = self
2244 .session
2245 .as_ref()
2246 .context("Client is not connected to any server")?;
2247 
2248 let mut messages = vec![ChatMessage::user(query)];
2249 let mut final_text = Vec::new();
2250 
2251 // Initial Claude API call with tools
2252 let mut chat_req = ChatRequest::new(messages.clone()).with_tools(self.tools.clone());
2253 let mut chat_rsp = self.request_model(&chat_req).await?;
2254 
2255 // Process response content - collect text and handle tool calls
2283 // Append tool responses to message history
2284 messages.push(ChatMessage::user(tool_results));
2285 
2286 // Build the next request and query model
2287 chat_req = ChatRequest::new(messages.clone());
2288 chat_rsp = self.request_model(&chat_req).await?;
2289 
2290 // Collect text from response
22562291 for text in chat_rsp.texts() {
22572292 final_text.push(text.to_string());
22582293 }
2259 
2260 let tool_calls = chat_rsp.tool_calls();
2261 if !tool_calls.is_empty() {
2262 // Append assistant's response to message history
2263 messages.push(ChatMessage::assistant(chat_rsp.content.clone()));
2264 
2265 // Execute each tool call and collect responses
2266 let mut tool_results = Vec::new();
2267 for tool_call in tool_calls {
2268 // Add information about the tool call to final text
2269 let tool_args_str = serde_json::to_string(&tool_call.fn_arguments)
2270 .unwrap_or_else(|_| "{}".to_string());
2271 
2272 final_text.push(format!(
2273 "[Calling tool {} with args {}]",
2274 tool_call.fn_name, tool_args_str
2275 ));
2276 
2277 // Query the MCP server
2278 let tool_result = session
2279 .call_tool(CallToolRequestParam {
2280 name: tool_call.fn_name.clone().into(),
2281 arguments: tool_call.fn_arguments.as_object().cloned(),
2282 })
2283 .await
2284 .with_context(|| format!("Tool call {} failed", tool_call.fn_name))?;
2285 
2286 let payload = serde_json::to_string(&tool_result)
2287 .context("Failed to serialize tool result")?;
2288 
2289 tool_results.push(ContentPart::ToolResponse(ToolResponse::new(
2290 tool_call.call_id.clone(),
2291 payload,
2292 )));
2293 }
2294 
2295 // Append tool responses to message history
2296 messages.push(ChatMessage::user(tool_results));
2297 
2298 // Build the next request and query model
2299 chat_req = ChatRequest::new(messages.clone());
2300 chat_rsp = self.request_model(&chat_req).await?;
2301 
2302 // Collect text from response
2303 for text in chat_rsp.texts() {
2304 final_text.push(text.to_string());
2305 }
2294 }
2295 
2296 Ok(final_text.join("\n"))
2297}
2298```
2299 
2300The method first sends the user's query and available tools to Claude. When Claude requests tools, the client executes each request through the MCP session, sends the results back to Claude, and collects the final text response.
2301 
2302### Interactive Chat Interface
2303 
2304Add the interactive terminal loop inside `impl MCPClient`:
2305 
2306```rust theme={null}
2307async fn chat_loop(&mut self) -> Result<()> {
2308 println!("\nMCP Client Started!");
2309 println!("Type your queries or 'quit' to exit.");
2310 
2311 let mut stdin = BufReader::new(io::stdin());
2312 let mut input = String::new();
2313 
2314 loop {
2315 print!("\nQuery: ");
2316 std::io::Write::flush(&mut std::io::stdout())?;
2317 
2318 input.clear();
2319 if stdin.read_line(&mut input).await? == 0 {
2320 break; // EOF
23062321 }
23072322 
2308 Ok(final_text.join("\n"))
2323 let query = input.trim();
2324 if query.eq_ignore_ascii_case("quit") {
2325 break;
2326 }
2327 if query.is_empty() {
2328 continue;
2329 }
2330 
2331 match self.process_query(query).await {
2332 Ok(response) => println!("\n{}", response),
2333 Err(err) => println!("\nError: {}", err),
2334 }
23092335 }
2310 ```
2311 
2312 The method first sends the user's query and available tools to Claude. When Claude requests tools, the client executes each request through the MCP session, sends the results back to Claude, and collects the final text response.
2313 
2314 ### Interactive Chat Interface
2315 
2316 Add the interactive terminal loop inside `impl MCPClient`:
2317 
2318 ```rust theme={null}
2319 async fn chat_loop(&mut self) -> Result<()> {
2320 println!("\nMCP Client Started!");
2321 println!("Type your queries or 'quit' to exit.");
2322 
2323 let mut stdin = BufReader::new(io::stdin());
2324 let mut input = String::new();
2325 
2326 loop {
2327 print!("\nQuery: ");
2328 std::io::Write::flush(&mut std::io::stdout())?;
2329 
2330 input.clear();
2331 if stdin.read_line(&mut input).await? == 0 {
2332 break; // EOF
2333 }
2334 
2335 let query = input.trim();
2336 if query.eq_ignore_ascii_case("quit") {
2337 break;
2338 }
2339 if query.is_empty() {
2340 continue;
2341 }
2342 
2343 match self.process_query(query).await {
2344 Ok(response) => println!("\n{}", response),
2345 Err(err) => println!("\nError: {}", err),
2346 }
2347 }
2348 
2349 Ok(())
2336 
2337 Ok(())
2338}
2339```
2340 
2341The loop accepts queries until the user types `quit` or closes standard input. Query errors are printed without terminating the client.
2342 
2343### Cleanup
2344 
2345Add this method inside `impl MCPClient` to stop the MCP session and child process:
2346 
2347```rust theme={null}
2348async fn cleanup(&mut self) -> Result<()> {
2349 if let Some(session) = self.session.take() {
2350 let _ = session.cancel().await;
23502351 }
2351 ```
2352 
2353 The loop accepts queries until the user types `quit` or closes standard input. Query errors are printed without terminating the client.
2354 
2355 ### Cleanup
2356 
2357 Add this method inside `impl MCPClient` to stop the MCP session and child process:
2358 
2359 ```rust theme={null}
2360 async fn cleanup(&mut self) -> Result<()> {
2361 if let Some(session) = self.session.take() {
2362 let _ = session.cancel().await;
2363 }
2364 Ok(())
2352 Ok(())
2353}
2354```
2355 
2356### Main Entry Point
2357 
2358Finally, add the asynchronous entry point outside the `impl MCPClient` block:
2359 
2360```rust theme={null}
2361#[tokio::main]
2362async fn main() -> Result<()> {
2363 dotenvy::dotenv().context("Failed to load env file")?;
2364 
2365 let mut args = std::env::args();
2366 let _ = args.next();
2367 let server_args: Vec<String> = args.collect();
2368 
2369 if server_args.is_empty() {
2370 eprintln!("Usage: cargo run -- <server_script_or_binary> [args...]");
2371 std::process::exit(1);
23652372 }
2366 ```
2367 
2368 ### Main Entry Point
2369 
2370 Finally, add the asynchronous entry point outside the `impl MCPClient` block:
2371 
2372 ```rust theme={null}
2373 #[tokio::main]
2374 async fn main() -> Result<()> {
2375 dotenvy::dotenv().context("Failed to load env file")?;
2376 
2377 let mut args = std::env::args();
2378 let _ = args.next();
2379 let server_args: Vec<String> = args.collect();
2380 
2381 if server_args.is_empty() {
2382 eprintln!("Usage: cargo run -- <server_script_or_binary> [args...]");
2383 std::process::exit(1);
2384 }
2385 
2386 let mut client = MCPClient::new()?;
2387 
2388 let result = async {
2389 client.connect_to_server(&server_args).await?;
2390 client.chat_loop().await
2391 }
2392 .await;
2393 
2394 let cleanup_result = client.cleanup().await;
2395 
2396 result?;
2397 cleanup_result?;
2398 
2399 Ok(())
2373 
2374 let mut client = MCPClient::new()?;
2375 
2376 let result = async {
2377 client.connect_to_server(&server_args).await?;
2378 client.chat_loop().await
24002379 }
2401 ```
2402 
2403 The entry point loads `.env`, treats all remaining command-line arguments as the server command, connects the client, starts the chat loop, and ensures cleanup runs before exiting.
2404 
2405 ### Verify the Complete File
2406 
2407 Before running the client, confirm the items in `src/main.rs` are placed at the correct scope:
2408 
2409 * `new`, `connect_to_server`, `process_query`, `request_model`, `chat_loop`, and `cleanup` are methods inside the single `impl MCPClient` block.
2410 * `main` and `convert_tools` are functions outside the `impl MCPClient` block.
2411 
2412 Rust does not require these items to appear in a particular order, but methods and free functions must be placed in the correct scope. Compare your file with the [complete `src/main.rs` example](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-rust/src/main.rs), then check that it compiles:
2413 
2414 ```bash theme={null}
2415 cargo fmt --check
2416 cargo check
2417 ```
2418 
2419 ## Running the Client
2420 
2421 Use `cargo run --` followed by the command you would normally use to start the MCP server:
2422 
2423 ```bash theme={null}
2424 # Python server
2425 cargo run -- python path/to/server.py
2426 
2427 # Node.js server
2428 cargo run -- node path/to/build/index.js
2429 
2430 # Executable server
2431 cargo run -- path/to/server-binary
2432 ```
2433 
2434 Running bare `cargo run` without a server command prints the usage message and exits.
2435 
2436 <Note>
2437 If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-rust), build the server first and then run a command similar to: `cargo run -- ../weather-server-rust/target/debug/weather`
2438 </Note>
2439 
2440 The client will:
2441 
2442 1. Start and connect to the specified MCP server
2443 2. List the tools available from that server
2444 3. Start an interactive chat session where you can:
2445 * Enter queries
2446 * See tool executions
2447 * Get responses from Claude
2448 
2449 ## How It Works
2450 
2451 When you submit a query:
2452 
2453 1. The client sends your query and the server's available tools to Claude
2454 2. Claude decides which tools, if any, to use
2455 3. The client executes requested tools through the MCP session
2456 4. Tool results are sent back to Claude
2457 5. Claude provides a natural language response
2458 6. The response is displayed in the terminal
2459 
2460 ## Best Practices
2461 
2462 1. **Error Handling**
2463 * Add context to errors at process, MCP, model API, and serialization boundaries
2464 * Report individual query errors without terminating the interactive session
2465 * Validate server commands before running them
2466 
2467 2. **Resource Management**
2468 * Always cancel the MCP session during cleanup
2469 * Ensure cleanup runs even when connection or chat-loop operations fail
2470 * Avoid starting a second server while a session is active
2471 
2472 3. **Security**
2473 * Store API keys securely in `.env`
2474 * Review the tools exposed by a server before allowing model-driven calls
2475 * Connect only to servers and executable commands you trust
2476 
2477 ## Troubleshooting
2478 
2479 ### Server Command Issues
2480 
2481 The arguments after `cargo run --` must form a complete command. Interpreted server scripts need their runtime:
2482 
2483 ```bash theme={null}
2484 # Correct
2485 cargo run -- python ./server/weather.py
2486 cargo run -- node ./server/build/index.js
2487 
2488 # Incorrect: a Python script is not necessarily executable by itself
2489 cargo run -- ./server/weather.py
2490 ```
2491 
2492 If a command cannot be found, use its absolute path or verify it is available in your `PATH`.
2493 
2494 ### Environment File Issues
2495 
2496 If you see `Failed to load env file`, ensure `.env` exists in the directory where you run the client.
2497 
2498 If the model request reports a missing API key, confirm that `.env` contains:
2499 
2500 ```text theme={null}
2501 ANTHROPIC_API_KEY=your-api-key-goes-here
2502 ```
2503 
2504 ### Tool and Response Errors
2505 
2506 * `Unable to list tools from server`: Verify the server starts successfully and communicates over stdio
2507 * `Tool call ... failed`: Verify the server tool's required arguments and environment variables
2508 * `Failed to serialize tool result`: Inspect the server's response for unsupported or malformed content
2509 </Tab>
2510</Tabs>
2380 .await;
2381 
2382 let cleanup_result = client.cleanup().await;
2383 
2384 result?;
2385 cleanup_result?;
2386 
2387 Ok(())
2388}
2389```
2390 
2391The entry point loads `.env`, treats all remaining command-line arguments as the server command, connects the client, starts the chat loop, and ensures cleanup runs before exiting.
2392 
2393### Verify the Complete File
2394 
2395Before running the client, confirm the items in `src/main.rs` are placed at the correct scope:
2396 
2397* `new`, `connect_to_server`, `process_query`, `request_model`, `chat_loop`, and `cleanup` are methods inside the single `impl MCPClient` block.
2398* `main` and `convert_tools` are functions outside the `impl MCPClient` block.
2399 
2400Rust does not require these items to appear in a particular order, but methods and free functions must be placed in the correct scope. Compare your file with the [complete `src/main.rs` example](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-rust/src/main.rs), then check that it compiles:
2401 
2402```bash theme={null}
2403cargo fmt --check
2404cargo check
2405```
2406 
2407## Running the Client
2408 
2409Use `cargo run --` followed by the command you would normally use to start the MCP server:
2410 
2411```bash theme={null}
2412# Python server
2413cargo run -- python path/to/server.py
2414 
2415# Node.js server
2416cargo run -- node path/to/build/index.js
2417 
2418# Executable server
2419cargo run -- path/to/server-binary
2420```
2421 
2422Running bare `cargo run` without a server command prints the usage message and exits.
2423 
2424> [!NOTE]
2425>
2426> If you're continuing [the weather tutorial from the server quickstart](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-rust), build the server first and then run a command similar to: `cargo run -- ../weather-server-rust/target/debug/weather`
2427 
2428The client will:
2429 
24301. Start and connect to the specified MCP server
24312. List the tools available from that server
24323. Start an interactive chat session where you can:
2433 * Enter queries
2434 * See tool executions
2435 * Get responses from Claude
2436 
2437## How It Works
2438 
2439When you submit a query:
2440 
24411. The client sends your query and the server's available tools to Claude
24422. Claude decides which tools, if any, to use
24433. The client executes requested tools through the MCP session
24444. Tool results are sent back to Claude
24455. Claude provides a natural language response
24466. The response is displayed in the terminal
2447 
2448## Best Practices
2449 
24501. **Error Handling**
2451 * Add context to errors at process, MCP, model API, and serialization boundaries
2452 * Report individual query errors without terminating the interactive session
2453 * Validate server commands before running them
2454 
24552. **Resource Management**
2456 * Always cancel the MCP session during cleanup
2457 * Ensure cleanup runs even when connection or chat-loop operations fail
2458 * Avoid starting a second server while a session is active
2459 
24603. **Security**
2461 * Store API keys securely in `.env`
2462 * Review the tools exposed by a server before allowing model-driven calls
2463 * Connect only to servers and executable commands you trust
2464 
2465## Troubleshooting
2466 
2467### Server Command Issues
2468 
2469The arguments after `cargo run --` must form a complete command. Interpreted server scripts need their runtime:
2470 
2471```bash theme={null}
2472# Correct
2473cargo run -- python ./server/weather.py
2474cargo run -- node ./server/build/index.js
2475 
2476# Incorrect: a Python script is not necessarily executable by itself
2477cargo run -- ./server/weather.py
2478```
2479 
2480If a command cannot be found, use its absolute path or verify it is available in your `PATH`.
2481 
2482### Environment File Issues
2483 
2484If you see `Failed to load env file`, ensure `.env` exists in the directory where you run the client.
2485 
2486If the model request reports a missing API key, confirm that `.env` contains:
2487 
2488```text theme={null}
2489ANTHROPIC_API_KEY=your-api-key-goes-here
2490```
2491 
2492### Tool and Response Errors
2493 
2494* `Unable to list tools from server`: Verify the server starts successfully and communicates over stdio
2495* `Tool call ... failed`: Verify the server tool's required arguments and environment variables
2496* `Failed to serialize tool result`: Inspect the server's response for unsupported or malformed content
25112497 
25122498## Next steps
25132499 
2514<CardGroup cols={2}>
2515 <Card title="Example servers" icon="grid" href="/examples">
2516 Check out our gallery of official MCP servers and implementations
2517 </Card>
2518</CardGroup>
2500> **[Example servers](/examples)**
2501>
2502> Check out our gallery of official MCP servers and implementations
25192503 

docs/2026-07-28/develop/build-server Changed · +2868 / -2936 lines

### Prerequisite knowledge ### Logging in MCP Servers ### Best Practices ### Quick Examples ### System requirements ### Set up your environment ## Building your server ### Importing packages and setting up the instance ### Helper functions ### Implementing tool execution ### Running the server ## Testing your server with Claude for Desktop ### Prerequisite knowledge ### Logging in MCP Servers ### Best Practices ### Quick Examples ### System requirements ### Set up your environment ## Building your server ### Importing packages and setting up constants ### Helper functions ### Implementing tool execution ### Running the server ## Testing your server with Claude for Desktop ### Logging in MCP Servers ### Best Practices ### System requirements ### Set up your environment ## Building your server ### Weather Service ### Create your Boot Application ### Running the server ## Testing your server with Claude for Desktop ## Testing your server with Java client ### Create an MCP Client manually ### Use MCP Client Boot Starter ## More Java MCP Server examples ### Prerequisite knowledge ### Logging in MCP Servers ### Best Practices ### System requirements ### Set up your environment ## Building your server ### Setting up the instance ### Weather API helper functions ### Implementing tool execution ### Running the server ## Testing your server with Claude for Desktop ### Prerequisite knowledge ### Logging in MCP Servers ### Best Practices ### System requirements ### Set up your environment ## Building your server ### Weather API helper functions ### Running the server ## Testing your server with Claude for Desktop ### Prerequisite knowledge ### Logging in MCP Servers ### Best Practices ### Quick Examples ### System requirements ### Set up your environment ## Building your server ### Importing packages and setting up constants ### Helper methods ### Implementing tool execution ### Running the server ## Testing your server with Claude for Desktop ### Prerequisite knowledge ### Logging in MCP Servers ### Best Practices ### Quick Examples ### System requirements ### Set up your environment ## Building your server ### Importing packages and constants ### Data structures ### Helper functions ### Implementing the Weather server and tools ### Implementing the ServerHandler ### Running the server ## Testing your server with Claude for Desktop ### Prerequisite knowledge ### Logging in MCP Servers ### Best Practices ### Quick Examples ### System requirements ### Set up your environment ## Building your server ### Importing packages and constants ### Data structures ### Helper functions ### Implementing tool execution ### Running the server ## Testing your server with Claude for Desktop

The two sides of this change are more than 400 edits apart, too far apart to line up, so this is the differ's own diff of it and the words inside a line are not marked.

from line 8
88 
99We'll build a server that exposes two tools: `get_alerts` and `get_forecast`. Then we'll connect the server to an MCP host (in this case, Claude for Desktop):
1010 
11<Frame>
12 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/current-weather.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=dce7b2f8a06c20ba358e4bd2e75fa4c7" width="2780" height="1849" data-path="images/current-weather.png" />
13</Frame>
14 
15<Note>
16 Servers can connect to any client. We've chosen Claude for Desktop here for simplicity, but we also have a guide on [building your own client](/docs/2026-07-28/develop/build-client).
17</Note>
11![](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/current-weather.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=dce7b2f8a06c20ba358e4bd2e75fa4c7)
12 
13> [!NOTE]
14>
15> Servers can connect to any client. We've chosen Claude for Desktop here for simplicity, but we also have a guide on [building your own client](/docs/2026-07-28/develop/build-client).
1816 
1917### Core MCP Concepts
2018 
from line 24
2624 
2725This tutorial will primarily focus on tools.
2826 
29<Tabs>
30 <Tab title="Python">
31 Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python)
32 
33 ### Prerequisite knowledge
34 
35 This quickstart assumes you have familiarity with:
36 
37 * Python
38 * LLMs like Claude
39 
40 ### Logging in MCP Servers
41 
42 When implementing MCP servers, be careful about how you handle logging:
43 
44 **For STDIO-based servers:** Never write to stdout. Writing to stdout will corrupt the JSON-RPC messages and break your server. The `print()` function writes to stdout by default, so keep it out of a STDIO server entirely.
45 
46 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
47 
48 ### Best Practices
49 
50 * Use the standard library `logging` module, which writes to stderr.
51 * Create one logger per module with `logging.getLogger(__name__)` and call it from your tools.
52 
53 ### Quick Examples
54 
55 ```python theme={null}
56 import logging
57 
58 logger = logging.getLogger(__name__)
59 
60 # ❌ Bad (STDIO)
61 print("Processing request")
62 
63 # ✅ Good (STDIO)
64 logger.info("Processing request") # writes to stderr
65 ```
66 
67 ### System requirements
68 
69 * Python 3.10 or higher installed.
70 * You must use the Python MCP SDK 2.0.0 or higher.
71 
72 ### Set up your environment
73 
74 First, let's install `uv` and set up our Python project and environment:
75 
76 <CodeGroup>
77 ```bash macOS/Linux theme={null}
78 curl -LsSf https://astral.sh/uv/install.sh | sh
79 ```
80 
81 ```powershell Windows theme={null}
82 powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
83 ```
84 </CodeGroup>
85 
86 Make sure to restart your terminal afterwards to ensure that the `uv` command gets picked up.
87 
88 Now, let's create and set up our project:
89 
90 <CodeGroup>
91 ```bash macOS/Linux theme={null}
92 # Create a new directory for our project
93 uv init weather
94 cd weather
95 
96 # Create virtual environment and activate it
97 uv venv
98 source .venv/bin/activate
99 
100 # Install dependencies
101 uv add "mcp[cli]"
102 
103 # Create our server file
104 touch weather.py
105 ```
106 
107 ```powershell Windows theme={null}
108 # Create a new directory for our project
109 uv init weather
110 cd weather
111 
112 # Create virtual environment and activate it
113 uv venv
114 .venv\Scripts\activate
115 
116 # Install dependencies
117 uv add mcp[cli]
118 
119 # Create our server file
120 new-item weather.py
121 ```
122 </CodeGroup>
123 
124 Now let's dive into building your server.
125 
126 ## Building your server
127 
128 ### Importing packages and setting up the instance
129 
130 Add these to the top of your `weather.py`:
131 
132 ```python theme={null}
133 from typing import Any
134 
135 import httpx2
136 from mcp.server import MCPServer
137 
138 # Initialize MCPServer
139 mcp = MCPServer("weather")
140 
141 # Constants
142 NWS_API_BASE = "https://api.weather.gov"
143 USER_AGENT = "weather-app/1.0"
144 ```
145 
146 `httpx2` is the HTTP client the SDK itself depends on, so installing `mcp` already brought it in.
147 
148 The MCPServer class uses Python type hints and docstrings to automatically generate tool definitions, making it easy to create and maintain MCP tools.
149 
150 ### Helper functions
151 
152 Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
153 
154 ```python theme={null}
155 async def make_nws_request(url: str) -> dict[str, Any] | None:
156 """Make a request to the NWS API with proper error handling."""
157 headers = {"User-Agent": USER_AGENT, "Accept": "application/geo+json"}
158 async with httpx2.AsyncClient() as client:
159 try:
160 response = await client.get(url, headers=headers, timeout=30.0)
161 response.raise_for_status()
162 return response.json()
163 except Exception:
164 return None
165 
166 
167 def format_alert(feature: dict) -> str:
168 """Format an alert feature into a readable string."""
169 props = feature["properties"]
170 return f"""
171 Event: {props.get("event", "Unknown")}
172 Area: {props.get("areaDesc", "Unknown")}
173 Severity: {props.get("severity", "Unknown")}
174 Description: {props.get("description", "No description available")}
175 Instructions: {props.get("instruction", "No specific instructions provided")}
27**Python**
28 
29Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python)
30 
31### Prerequisite knowledge
32 
33This quickstart assumes you have familiarity with:
34 
35* Python
36* LLMs like Claude
37 
38### Logging in MCP Servers
39 
40When implementing MCP servers, be careful about how you handle logging:
41 
42**For STDIO-based servers:** Never write to stdout. Writing to stdout will corrupt the JSON-RPC messages and break your server. The `print()` function writes to stdout by default, so keep it out of a STDIO server entirely.
43 
44**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
45 
46### Best Practices
47 
48* Use the standard library `logging` module, which writes to stderr.
49* Create one logger per module with `logging.getLogger(__name__)` and call it from your tools.
50 
51### Quick Examples
52 
53```python theme={null}
54import logging
55 
56logger = logging.getLogger(__name__)
57 
58# ❌ Bad (STDIO)
59print("Processing request")
60 
61# ✅ Good (STDIO)
62logger.info("Processing request") # writes to stderr
63```
64 
65### System requirements
66 
67* Python 3.10 or higher installed.
68* You must use the Python MCP SDK 2.0.0 or higher.
69 
70### Set up your environment
71 
72First, let's install `uv` and set up our Python project and environment:
73 
74```bash macOS/Linux theme={null}
75curl -LsSf https://astral.sh/uv/install.sh | sh
76```
77 
78```powershell Windows theme={null}
79powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
80```
81 
82Make sure to restart your terminal afterwards to ensure that the `uv` command gets picked up.
83 
84Now, let's create and set up our project:
85 
86```bash macOS/Linux theme={null}
87# Create a new directory for our project
88uv init weather
89cd weather
90 
91# Create virtual environment and activate it
92uv venv
93source .venv/bin/activate
94 
95# Install dependencies
96uv add "mcp[cli]"
97 
98# Create our server file
99touch weather.py
100```
101 
102```powershell Windows theme={null}
103# Create a new directory for our project
104uv init weather
105cd weather
106 
107# Create virtual environment and activate it
108uv venv
109.venv\Scripts\activate
110 
111# Install dependencies
112uv add mcp[cli]
113 
114# Create our server file
115new-item weather.py
116```
117 
118Now let's dive into building your server.
119 
120## Building your server
121 
122### Importing packages and setting up the instance
123 
124Add these to the top of your `weather.py`:
125 
126```python theme={null}
127from typing import Any
128 
129import httpx2
130from mcp.server import MCPServer
131 
132# Initialize MCPServer
133mcp = MCPServer("weather")
134 
135# Constants
136NWS_API_BASE = "https://api.weather.gov"
137USER_AGENT = "weather-app/1.0"
138```
139 
140`httpx2` is the HTTP client the SDK itself depends on, so installing `mcp` already brought it in.
141 
142The MCPServer class uses Python type hints and docstrings to automatically generate tool definitions, making it easy to create and maintain MCP tools.
143 
144### Helper functions
145 
146Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
147 
148```python theme={null}
149async def make_nws_request(url: str) -> dict[str, Any] | None:
150 """Make a request to the NWS API with proper error handling."""
151 headers = {"User-Agent": USER_AGENT, "Accept": "application/geo+json"}
152 async with httpx2.AsyncClient() as client:
153 try:
154 response = await client.get(url, headers=headers, timeout=30.0)
155 response.raise_for_status()
156 return response.json()
157 except Exception:
158 return None
159 
160 
161def format_alert(feature: dict) -> str:
162 """Format an alert feature into a readable string."""
163 props = feature["properties"]
164 return f"""
165Event: {props.get("event", "Unknown")}
166Area: {props.get("areaDesc", "Unknown")}
167Severity: {props.get("severity", "Unknown")}
168Description: {props.get("description", "No description available")}
169Instructions: {props.get("instruction", "No specific instructions provided")}
170"""
171```
172 
173### Implementing tool execution
174 
175The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
176 
177```python theme={null}
178@mcp.tool()
179async def get_alerts(state: str) -> str:
180 """Get weather alerts for a US state.
181 
182 Args:
183 state: Two-letter US state code (e.g. CA, NY)
176184 """
177 ```
178 
179 ### Implementing tool execution
180 
181 The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
182 
183 ```python theme={null}
184 @mcp.tool()
185 async def get_alerts(state: str) -> str:
186 """Get weather alerts for a US state.
187 
188 Args:
189 state: Two-letter US state code (e.g. CA, NY)
185 url = f"{NWS_API_BASE}/alerts/active/area/{state}"
186 data = await make_nws_request(url)
187 
188 if not data or "features" not in data:
189 return "Unable to fetch alerts or no alerts found."
190 
191 if not data["features"]:
192 return "No active alerts for this state."
193 
194 alerts = [format_alert(feature) for feature in data["features"]]
195 return "\n---\n".join(alerts)
196 
197 
198@mcp.tool()
199async def get_forecast(latitude: float, longitude: float) -> str:
200 """Get weather forecast for a location.
201 
202 Args:
203 latitude: Latitude of the location
204 longitude: Longitude of the location
205 """
206 # First get the forecast grid endpoint
207 points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
208 points_data = await make_nws_request(points_url)
209 
210 if not points_data:
211 return "Unable to fetch forecast data for this location."
212 
213 # Get the forecast URL from the points response
214 forecast_url = points_data["properties"]["forecast"]
215 forecast_data = await make_nws_request(forecast_url)
216 
217 if not forecast_data:
218 return "Unable to fetch detailed forecast."
219 
220 # Format the periods into a readable forecast
221 periods = forecast_data["properties"]["periods"]
222 forecasts = []
223 for period in periods[:5]: # Only show next 5 periods
224 forecast = f"""
225{period["name"]}:
226Temperature: {period["temperature"]}°{period["temperatureUnit"]}
227Wind: {period["windSpeed"]} {period["windDirection"]}
228Forecast: {period["detailedForecast"]}
229"""
230 forecasts.append(forecast)
231 
232 return "\n---\n".join(forecasts)
233```
234 
235### Running the server
236 
237Finally, let's initialize and run the server:
238 
239```python theme={null}
240if __name__ == "__main__":
241 mcp.run(transport="stdio")
242```
243 
244Your server is complete! Run `uv run weather.py` to start the MCP server, which will listen for messages from MCP hosts.
245 
246Let's now test your server from an existing MCP host, Claude for Desktop.
247 
248## Testing your server with Claude for Desktop
249 
250First, make sure you have Claude for Desktop installed. [You can install the latest version
251here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
252 
253We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
254 
255For example, if you have [VS Code](https://code.visualstudio.com/) installed:
256 
257```bash Linux theme={null}
258code ~/.config/Claude/claude_desktop_config.json
259```
260 
261```bash macOS theme={null}
262code ~/Library/Application\ Support/Claude/claude_desktop_config.json
263```
264 
265```powershell Windows theme={null}
266code $env:AppData\Claude\claude_desktop_config.json
267```
268 
269You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
270 
271In this case, we'll add our single weather server like so:
272 
273```json macOS/Linux theme={null}
274{
275 "mcpServers": {
276 "weather": {
277 "command": "uv",
278 "args": [
279 "--directory",
280 "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
281 "run",
282 "weather.py"
283 ]
284 }
285 }
286}
287```
288 
289```json Windows theme={null}
290{
291 "mcpServers": {
292 "weather": {
293 "command": "uv",
294 "args": [
295 "--directory",
296 "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather",
297 "run",
298 "weather.py"
299 ]
300 }
301 }
302}
303```
304 
305> [!WARNING]
306>
307> You may need to put the full path to the `uv` executable in the `command` field. You can get this by running `which uv` on macOS/Linux or `where uv` on Windows.
308 
309> [!NOTE]
310>
311> Make sure you pass in the absolute path to your server. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path.
312 
313This tells Claude for Desktop:
314 
3151. There's an MCP server named "weather"
3162. To launch it by running `uv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather.py`
317 
318Save the file, and restart **Claude for Desktop**.
319 
320**TypeScript**
321 
322Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript)
323 
324### Prerequisite knowledge
325 
326This quickstart assumes you have familiarity with:
327 
328* TypeScript
329* LLMs like Claude
330 
331### Logging in MCP Servers
332 
333When implementing MCP servers, be careful about how you handle logging:
334 
335**For STDIO-based servers:** Never use `console.log()`, as it writes to standard output (stdout) by default. Writing to stdout will corrupt the JSON-RPC messages and break your server.
336 
337**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
338 
339### Best Practices
340 
341* Use `console.error()` which writes to stderr, or use a logging library that writes to stderr or files.
342 
343### Quick Examples
344 
345```javascript theme={null}
346// ❌ Bad (STDIO)
347console.log("Server started");
348 
349// ✅ Good (STDIO)
350console.error("Server started"); // stderr is safe
351```
352 
353### System requirements
354 
355For TypeScript, make sure you have the latest version of Node installed.
356 
357### Set up your environment
358 
359First, let's install Node.js and npm if you haven't already. You can download them from [nodejs.org](https://nodejs.org/).
360Verify your Node.js installation:
361 
362```bash theme={null}
363node --version
364npm --version
365```
366 
367For this tutorial, you'll need Node.js version 20 or higher.
368 
369Now, let's create and set up our project:
370 
371```bash macOS/Linux theme={null}
372# Create a new directory for our project
373mkdir weather
374cd weather
375 
376# Initialize a new npm project
377npm init -y
378 
379# Install dependencies
380npm install @modelcontextprotocol/server zod
381npm install -D @types/node typescript
382 
383# Create our files
384mkdir src
385touch src/index.ts
386```
387 
388```powershell Windows theme={null}
389# Create a new directory for our project
390md weather
391cd weather
392 
393# Initialize a new npm project
394npm init -y
395 
396# Install dependencies
397npm install @modelcontextprotocol/server zod
398npm install -D @types/node typescript
399 
400# Create our files
401md src
402new-item src\index.ts
403```
404 
405Update your package.json to add type: "module" and a build script:
406 
407```json package.json theme={null}
408{
409 "type": "module",
410 "bin": {
411 "weather": "./build/index.js"
412 },
413 "scripts": {
414 "build": "tsc && chmod 755 build/index.js"
415 },
416 "files": ["build"]
417}
418```
419 
420Create a `tsconfig.json` in the root of your project:
421 
422```json tsconfig.json theme={null}
423{
424 "compilerOptions": {
425 "target": "ES2022",
426 "module": "Node16",
427 "moduleResolution": "Node16",
428 "types": ["node"],
429 "outDir": "./build",
430 "rootDir": "./src",
431 "strict": true,
432 "esModuleInterop": true,
433 "skipLibCheck": true,
434 "forceConsistentCasingInFileNames": true
435 },
436 "include": ["src/**/*"],
437 "exclude": ["node_modules"]
438}
439```
440 
441Now let's dive into building your server.
442 
443## Building your server
444 
445### Importing packages and setting up constants
446 
447Add these to the top of your `src/index.ts`:
448 
449```typescript theme={null}
450import { McpServer } from "@modelcontextprotocol/server";
451import { serveStdio } from "@modelcontextprotocol/server/stdio";
452import { z } from "zod";
453 
454const NWS_API_BASE = "https://api.weather.gov";
455const USER_AGENT = "weather-app/1.0";
456```
457 
458### Helper functions
459 
460Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
461 
462```typescript theme={null}
463// Helper function for making NWS API requests
464async function makeNWSRequest<T>(url: string): Promise<T | null> {
465 const headers = {
466 "User-Agent": USER_AGENT,
467 Accept: "application/geo+json",
468 };
469 
470 try {
471 const response = await fetch(url, { headers });
472 if (!response.ok) {
473 throw new Error(`HTTP error! status: ${response.status}`);
474 }
475 return (await response.json()) as T;
476 } catch (error) {
477 console.error("Error making NWS request:", error);
478 return null;
479 }
480}
481 
482interface AlertFeature {
483 properties: {
484 event?: string;
485 areaDesc?: string;
486 severity?: string;
487 status?: string;
488 headline?: string;
489 };
490}
491 
492// Format alert data
493function formatAlert(feature: AlertFeature): string {
494 const props = feature.properties;
495 return [
496 `Event: ${props.event || "Unknown"}`,
497 `Area: ${props.areaDesc || "Unknown"}`,
498 `Severity: ${props.severity || "Unknown"}`,
499 `Status: ${props.status || "Unknown"}`,
500 `Headline: ${props.headline || "No headline"}`,
501 "---",
502 ].join("\n");
503}
504 
505interface ForecastPeriod {
506 name?: string;
507 temperature?: number;
508 temperatureUnit?: string;
509 windSpeed?: string;
510 windDirection?: string;
511 shortForecast?: string;
512}
513 
514interface AlertsResponse {
515 features: AlertFeature[];
516}
517 
518interface PointsResponse {
519 properties: {
520 forecast?: string;
521 };
522}
523 
524interface ForecastResponse {
525 properties: {
526 periods: ForecastPeriod[];
527 };
528}
529```
530 
531### Implementing tool execution
532 
533The tool execution handler is responsible for actually executing the logic of each tool. Let's add it, inside a `createServer()` function that builds the server instance and registers both tools on it:
534 
535```typescript theme={null}
536// Build a server instance and register its tools. serveStdio calls this
537// whenever it needs an instance, so every call must return a fresh one.
538function createServer() {
539 const server = new McpServer({
540 name: "weather",
541 version: "1.0.0",
542 });
543 
544 server.registerTool(
545 "get_alerts",
546 {
547 description: "Get weather alerts for a state",
548 inputSchema: z.object({
549 state: z
550 .string()
551 .length(2)
552 .describe("Two-letter state code (e.g. CA, NY)"),
553 }),
554 },
555 async ({ state }) => {
556 const stateCode = state.toUpperCase();
557 const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`;
558 const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl);
559 
560 if (!alertsData) {
561 return {
562 content: [
563 {
564 type: "text",
565 text: "Failed to retrieve alerts data",
566 },
567 ],
568 };
569 }
570 
571 const features = alertsData.features || [];
572 if (!features.length) {
573 return {
574 content: [
575 {
576 type: "text",
577 text: `No active alerts for ${stateCode}`,
578 },
579 ],
580 };
581 }
582 
583 const formattedAlerts = features.map(formatAlert);
584 const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join("\n")}`;
585 
586 return {
587 content: [
588 {
589 type: "text",
590 text: alertsText,
591 },
592 ],
593 };
594 },
595 );
596 
597 server.registerTool(
598 "get_forecast",
599 {
600 description: "Get weather forecast for a location",
601 inputSchema: z.object({
602 latitude: z
603 .number()
604 .min(-90)
605 .max(90)
606 .describe("Latitude of the location"),
607 longitude: z
608 .number()
609 .min(-180)
610 .max(180)
611 .describe("Longitude of the location"),
612 }),
613 },
614 async ({ latitude, longitude }) => {
615 // Get grid point data
616 const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`;
617 const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl);
618 
619 if (!pointsData) {
620 return {
621 content: [
622 {
623 type: "text",
624 text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`,
625 },
626 ],
627 };
628 }
629 
630 const forecastUrl = pointsData.properties?.forecast;
631 if (!forecastUrl) {
632 return {
633 content: [
634 {
635 type: "text",
636 text: "Failed to get forecast URL from grid point data",
637 },
638 ],
639 };
640 }
641 
642 // Get forecast data
643 const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl);
644 if (!forecastData) {
645 return {
646 content: [
647 {
648 type: "text",
649 text: "Failed to retrieve forecast data",
650 },
651 ],
652 };
653 }
654 
655 const periods = forecastData.properties?.periods || [];
656 if (periods.length === 0) {
657 return {
658 content: [
659 {
660 type: "text",
661 text: "No forecast periods available",
662 },
663 ],
664 };
665 }
666 
667 // Format forecast periods
668 const formattedForecast = periods.map((period: ForecastPeriod) =>
669 [
670 `${period.name || "Unknown"}:`,
671 `Temperature: ${period.temperature || "Unknown"}°${period.temperatureUnit || "F"}`,
672 `Wind: ${period.windSpeed || "Unknown"} ${period.windDirection || ""}`,
673 `${period.shortForecast || "No forecast available"}`,
674 "---",
675 ].join("\n"),
676 );
677 
678 const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join("\n")}`;
679 
680 return {
681 content: [
682 {
683 type: "text",
684 text: forecastText,
685 },
686 ],
687 };
688 },
689 );
690 
691 return server;
692}
693```
694 
695### Running the server
696 
697Finally, serve the server over stdio:
698 
699```typescript theme={null}
700serveStdio(createServer, {
701 onerror: (error) => console.error("Weather MCP Server error:", error),
702});
703console.error("Weather MCP Server running on stdio");
704```
705 
706`serveStdio` negotiates the protocol revision with each client, so the same server answers both 2026-07-28 clients and clients that still open with the 2025-era `initialize` handshake. It calls `createServer()` whenever it needs an instance, including once for a `server/discover` probe that is discarded if the client falls back to `initialize`, which is why the factory returns a new `McpServer` on every call. Wiring the server by hand with `server.connect(new StdioServerTransport())` still compiles, but a server started that way only serves 2025-era clients.
707 
708Make sure to run `npm run build` to build your server! This is a very important step in getting your server to connect.
709 
710To check that the server answers 2026-07-28 clients, list its tools with the [Inspector CLI](/docs/2026-07-28/tools/inspector/cli) in the `modern` [protocol era](/docs/2026-07-28/tools/inspector/protocol-eras):
711 
712```bash theme={null}
713npx @modelcontextprotocol/inspector --cli node build/index.js --protocol-era modern --method tools/list
714```
715 
716The Inspector defaults to the `legacy` era, which only exercises the 2025-era handshake, so run the same command once more with `--protocol-era legacy`. Both runs list `get_alerts` and `get_forecast`.
717 
718Let's now test your server from an existing MCP host, Claude for Desktop.
719 
720## Testing your server with Claude for Desktop
721 
722First, make sure you have Claude for Desktop installed. [You can install the latest version
723here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
724 
725We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
726 
727For example, if you have [VS Code](https://code.visualstudio.com/) installed:
728 
729```bash Linux theme={null}
730code ~/.config/Claude/claude_desktop_config.json
731```
732 
733```bash macOS theme={null}
734code ~/Library/Application\ Support/Claude/claude_desktop_config.json
735```
736 
737```powershell Windows theme={null}
738code $env:AppData\Claude\claude_desktop_config.json
739```
740 
741You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
742 
743In this case, we'll add our single weather server like so:
744 
745```json macOS/Linux theme={null}
746{
747 "mcpServers": {
748 "weather": {
749 "command": "node",
750 "args": ["/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js"]
751 }
752 }
753}
754```
755 
756```json Windows theme={null}
757{
758 "mcpServers": {
759 "weather": {
760 "command": "node",
761 "args": ["C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\index.js"]
762 }
763 }
764}
765```
766 
767This tells Claude for Desktop:
768 
7691. There's an MCP server named "weather"
7702. Launch it by running `node /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js`
771 
772Save the file, and restart **Claude for Desktop**.
773 
774**Java**
775 
776> [!NOTE]
777>
778> This is a quickstart demo based on Spring AI MCP auto-configuration and boot starters.
779> To learn how to create sync and async MCP Servers, manually, consult the [Java SDK Server](https://java.sdk.modelcontextprotocol.io/) documentation.
780 
781Let's get started with building our weather server!
782[You can find the complete code for what we'll be building here.](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-stdio-server)
783 
784For more information, see the [MCP Server Boot Starter](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html) reference documentation.
785For manual MCP Server implementation, refer to the [MCP Server Java SDK documentation](https://java.sdk.modelcontextprotocol.io/).
786 
787### Logging in MCP Servers
788 
789When implementing MCP servers, be careful about how you handle logging:
790 
791**For STDIO-based servers:** Never use `System.out.println()` or `System.out.print()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
792 
793**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
794 
795### Best Practices
796 
797* Use a logging library that writes to stderr or files.
798* Ensure any configured logging library will not write to stdout.
799 
800### System requirements
801 
802* Java 17 or higher installed.
803* [Spring Boot 3.3.x](https://docs.spring.io/spring-boot/installing.html) or higher
804 
805### Set up your environment
806 
807Use the [Spring Initializer](https://start.spring.io/) to bootstrap the project.
808 
809You will need to add the following dependencies:
810 
811```xml Maven theme={null}
812<dependencies>
813 <dependency>
814 <groupId>org.springframework.ai</groupId>
815 <artifactId>spring-ai-starter-mcp-server</artifactId>
816 </dependency>
817 
818 <dependency>
819 <groupId>org.springframework</groupId>
820 <artifactId>spring-web</artifactId>
821 </dependency>
822</dependencies>
823```
824 
825```groovy Gradle theme={null}
826dependencies {
827 implementation platform("org.springframework.ai:spring-ai-starter-mcp-server")
828 implementation platform("org.springframework:spring-web")
829}
830```
831 
832Then configure your application by setting the application properties:
833 
834```bash application.properties theme={null}
835spring.main.bannerMode=off
836logging.pattern.console=
837```
838 
839```yaml application.yml theme={null}
840logging:
841 pattern:
842 console:
843spring:
844 main:
845 banner-mode: off
846```
847 
848The [Server Configuration Properties](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html#_configuration_properties) documents all available properties.
849 
850Now let's dive into building your server.
851 
852## Building your server
853 
854### Weather Service
855 
856Let's implement a [WeatherService.java](https://github.com/spring-projects/spring-ai-examples/blob/main/model-context-protocol/weather/starter-stdio-server/src/main/java/org/springframework/ai/mcp/sample/server/WeatherService.java) that uses a REST client to query the data from the National Weather Service API:
857 
858```java theme={null}
859@Service
860public class WeatherService {
861 
862 private final RestClient restClient;
863 
864 public WeatherService() {
865 this.restClient = RestClient.builder()
866 .baseUrl("https://api.weather.gov")
867 .defaultHeader("Accept", "application/geo+json")
868 .defaultHeader("User-Agent", "WeatherApiClient/1.0 ([email protected])")
869 .build();
870 }
871 
872 @Tool(description = "Get weather forecast for a specific latitude/longitude")
873 public String getWeatherForecastByLocation(
874 double latitude, // Latitude coordinate
875 double longitude // Longitude coordinate
876 ) {
877 // Returns detailed forecast including:
878 // - Temperature and unit
879 // - Wind speed and direction
880 // - Detailed forecast description
881 }
882 
883 @Tool(description = "Get weather alerts for a US state")
884 public String getAlerts(
885 @ToolParam(description = "Two-letter US state code (e.g. CA, NY)") String state
886 ) {
887 // Returns active alerts including:
888 // - Event type
889 // - Affected area
890 // - Severity
891 // - Description
892 // - Safety instructions
893 }
894 
895 // ......
896}
897```
898 
899The `@Service` annotation will auto-register the service in your application context.
900The Spring AI `@Tool` annotation makes it easy to create and maintain MCP tools.
901 
902The auto-configuration will automatically register these tools with the MCP server.
903 
904### Create your Boot Application
905 
906```java theme={null}
907@SpringBootApplication
908public class McpServerApplication {
909 
910 public static void main(String[] args) {
911 SpringApplication.run(McpServerApplication.class, args);
912 }
913 
914 @Bean
915 public ToolCallbackProvider weatherTools(WeatherService weatherService) {
916 return MethodToolCallbackProvider.builder().toolObjects(weatherService).build();
917 }
918}
919```
920 
921Uses the `MethodToolCallbackProvider` utils to convert the `@Tools` into actionable callbacks used by the MCP server.
922 
923### Running the server
924 
925Finally, let's build the server:
926 
927```bash theme={null}
928./mvnw clean install
929```
930 
931This will generate an `mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar` file within the `target` folder.
932 
933Let's now test your server from an existing MCP host, Claude for Desktop.
934 
935## Testing your server with Claude for Desktop
936 
937First, make sure you have Claude for Desktop installed.
938[You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
939 
940We'll need to configure Claude for Desktop for whichever MCP servers you want to use.
941To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor.
942Make sure to create the file if it doesn't exist.
943 
944For example, if you have [VS Code](https://code.visualstudio.com/) installed:
945 
946```bash Linux theme={null}
947code ~/.config/Claude/claude_desktop_config.json
948```
949 
950```bash macOS theme={null}
951code ~/Library/Application\ Support/Claude/claude_desktop_config.json
952```
953 
954```powershell Windows theme={null}
955code $env:AppData\Claude\claude_desktop_config.json
956```
957 
958You'll then add your servers in the `mcpServers` key.
959The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
960 
961In this case, we'll add our single weather server like so:
962 
963```json macOS/Linux theme={null}
964{
965 "mcpServers": {
966 "spring-ai-mcp-weather": {
967 "command": "java",
968 "args": [
969 "-Dspring.ai.mcp.server.stdio=true",
970 "-jar",
971 "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
972 ]
973 }
974 }
975}
976```
977 
978```json Windows theme={null}
979{
980 "mcpServers": {
981 "spring-ai-mcp-weather": {
982 "command": "java",
983 "args": [
984 "-Dspring.ai.mcp.server.transport=STDIO",
985 "-jar",
986 "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
987 ]
988 }
989 }
990}
991```
992 
993> [!NOTE]
994>
995> Make sure you pass in the absolute path to your server.
996 
997This tells Claude for Desktop:
998 
9991. There's an MCP server named "my-weather-server"
10002. To launch it by running `java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar`
1001 
1002Save the file, and restart **Claude for Desktop**.
1003 
1004## Testing your server with Java client
1005 
1006### Create an MCP Client manually
1007 
1008Use the `McpClient` to connect to the server:
1009 
1010```java theme={null}
1011var stdioParams = ServerParameters.builder("java")
1012 .args("-jar", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar")
1013 .build();
1014 
1015var stdioTransport = new StdioClientTransport(stdioParams);
1016 
1017var mcpClient = McpClient.sync(stdioTransport).build();
1018 
1019mcpClient.initialize();
1020 
1021ListToolsResult toolsList = mcpClient.listTools();
1022 
1023CallToolResult weather = mcpClient.callTool(
1024 new CallToolRequest("getWeatherForecastByLocation",
1025 Map.of("latitude", "47.6062", "longitude", "-122.3321")));
1026 
1027CallToolResult alert = mcpClient.callTool(
1028 new CallToolRequest("getAlerts", Map.of("state", "NY")));
1029 
1030mcpClient.closeGracefully();
1031```
1032 
1033### Use MCP Client Boot Starter
1034 
1035Create a new boot starter application using the `spring-ai-starter-mcp-client` dependency:
1036 
1037```xml theme={null}
1038<dependency>
1039 <groupId>org.springframework.ai</groupId>
1040 <artifactId>spring-ai-starter-mcp-client</artifactId>
1041</dependency>
1042```
1043 
1044and set the `spring.ai.mcp.client.stdio.servers-configuration` property to point to your `claude_desktop_config.json`.
1045You can reuse the existing Anthropic Desktop configuration:
1046 
1047```properties theme={null}
1048spring.ai.mcp.client.stdio.servers-configuration=file:PATH/TO/claude_desktop_config.json
1049```
1050 
1051When you start your client application, the auto-configuration will automatically create MCP clients from the claude\_desktop\_config.json.
1052 
1053For more information, see the [MCP Client Boot Starters](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-client-boot-starter-docs.html) reference documentation.
1054 
1055## More Java MCP Server examples
1056 
1057The [starter-webflux-server](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-webflux-server) demonstrates how to create an HTTP-based MCP server with the WebFlux starter.
1058Set the `spring.ai.mcp.server.protocol=STREAMABLE` property to serve it over Streamable HTTP.
1059It showcases how to define and register MCP Tools, Resources, and Prompts, using the Spring Boot's auto-configuration capabilities.
1060 
1061**Kotlin**
1062 
1063Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/weather-stdio-server)
1064 
1065### Prerequisite knowledge
1066 
1067This quickstart assumes you have familiarity with:
1068 
1069* Kotlin
1070* LLMs like Claude
1071 
1072### Logging in MCP Servers
1073 
1074When implementing MCP servers, be careful about how you handle logging:
1075 
1076**For STDIO-based servers:** Never use `println()`, as it writes to standard output (stdout) by default. Writing to stdout will corrupt the JSON-RPC messages and break your server.
1077 
1078**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
1079 
1080### Best Practices
1081 
1082* Use a logging library that writes to stderr or files.
1083 
1084### System requirements
1085 
1086* JDK 11 or higher installed.
1087 
1088### Set up your environment
1089 
1090First, let's install `java` and `gradle` if you haven't already.
1091You can download `java` from [official Oracle JDK website](https://www.oracle.com/java/technologies/downloads/).
1092Verify your `java` installation:
1093 
1094```bash theme={null}
1095java --version
1096```
1097 
1098Now, let's create and set up your project:
1099 
1100```bash macOS/Linux theme={null}
1101# Create a new directory for our project
1102mkdir weather
1103cd weather
1104 
1105# Initialize a new kotlin project
1106gradle init
1107```
1108 
1109```powershell Windows theme={null}
1110# Create a new directory for our project
1111md weather
1112cd weather
1113 
1114# Initialize a new kotlin project
1115gradle init
1116```
1117 
1118After running `gradle init`, select **Application** as the project type, **Kotlin** as the programming language.
1119 
1120Alternatively, you can create a Kotlin application using the [IntelliJ IDEA project wizard](https://kotlinlang.org/docs/jvm-get-started.html).
1121 
1122After creating the project, replace the contents of your `build.gradle.kts` with:
1123 
1124```kotlin build.gradle.kts theme={null}
1125// Check latest versions at https://github.com/modelcontextprotocol/kotlin-sdk/releases
1126val mcpVersion = "0.9.0"
1127val ktorVersion = "3.2.3"
1128val slf4jVersion = "2.0.17"
1129 
1130plugins {
1131 kotlin("jvm") version "2.3.20"
1132 kotlin("plugin.serialization") version "2.3.20"
1133 id("com.gradleup.shadow") version "8.3.9"
1134 application
1135}
1136 
1137application {
1138 mainClass.set("MainKt")
1139}
1140 
1141dependencies {
1142 implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion")
1143 implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion")
1144 implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")
1145 implementation("io.ktor:ktor-client-cio:$ktorVersion")
1146 implementation("org.slf4j:slf4j-simple:$slf4jVersion")
1147}
1148```
1149 
1150Verify that everything is set up correctly:
1151 
1152```bash theme={null}
1153./gradlew build
1154```
1155 
1156Now let's dive into building your server.
1157 
1158## Building your server
1159 
1160### Setting up the instance
1161 
1162Add a server initialization function:
1163 
1164```kotlin theme={null}
1165fun runMcpServer() {
1166 val server = Server(
1167 Implementation(
1168 name = "weather",
1169 version = "1.0.0",
1170 ),
1171 ServerOptions(
1172 capabilities = ServerCapabilities(tools = ServerCapabilities.Tools(listChanged = true)),
1173 ),
1174 )
1175 
1176 // register tools on server here
1177 
1178 val transport = StdioServerTransport(
1179 System.`in`.asInput(),
1180 System.out.asSink().buffered(),
1181 )
1182 
1183 runBlocking {
1184 val session = server.createSession(transport)
1185 val done = Job()
1186 session.onClose {
1187 done.complete()
1188 }
1189 done.join()
1190 }
1191}
1192```
1193 
1194### Weather API helper functions
1195 
1196Next, let's add functions and data classes for querying and converting responses from the National Weather Service API:
1197 
1198```kotlin theme={null}
1199val httpClient = HttpClient(CIO) {
1200 defaultRequest {
1201 url("https://api.weather.gov")
1202 headers {
1203 append("Accept", "application/geo+json")
1204 append("User-Agent", "WeatherApiClient/1.0")
1205 }
1206 contentType(ContentType.Application.Json)
1207 }
1208 install(ContentNegotiation) {
1209 json(Json { ignoreUnknownKeys = true })
1210 }
1211}
1212 
1213// Extension function to fetch weather alerts for a given state
1214suspend fun HttpClient.getAlerts(state: String): List<String> {
1215 val alerts = this.get("/alerts/active/area/$state").body<AlertsResponse>()
1216 return alerts.features.map { feature ->
1901217 """
191 url = f"{NWS_API_BASE}/alerts/active/area/{state}"
192 data = await make_nws_request(url)
193 
194 if not data or "features" not in data:
195 return "Unable to fetch alerts or no alerts found."
196 
197 if not data["features"]:
198 return "No active alerts for this state."
199 
200 alerts = [format_alert(feature) for feature in data["features"]]
201 return "\n---\n".join(alerts)
202 
203 
204 @mcp.tool()
205 async def get_forecast(latitude: float, longitude: float) -> str:
206 """Get weather forecast for a location.
207 
208 Args:
209 latitude: Latitude of the location
210 longitude: Longitude of the location
1218 Event: ${feature.properties.event}
1219 Area: ${feature.properties.areaDesc}
1220 Severity: ${feature.properties.severity}
1221 Status: ${feature.properties.status}
1222 Headline: ${feature.properties.headline}
1223 """.trimIndent()
1224 }
1225}
1226 
1227// Extension function to fetch forecast information for given latitude and longitude
1228suspend fun HttpClient.getForecast(latitude: Double, longitude: Double): List<String> {
1229 val points = this.get("/points/$latitude,$longitude").body<PointsResponse>()
1230 val forecastUrl = points.properties.forecast ?: error("No forecast URL available")
1231 val forecast = this.get(forecastUrl).body<ForecastResponse>()
1232 return forecast.properties.periods.map { period ->
2111233 """
212 # First get the forecast grid endpoint
213 points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
214 points_data = await make_nws_request(points_url)
215 
216 if not points_data:
217 return "Unable to fetch forecast data for this location."
218 
219 # Get the forecast URL from the points response
220 forecast_url = points_data["properties"]["forecast"]
221 forecast_data = await make_nws_request(forecast_url)
222 
223 if not forecast_data:
224 return "Unable to fetch detailed forecast."
225 
226 # Format the periods into a readable forecast
227 periods = forecast_data["properties"]["periods"]
228 forecasts = []
229 for period in periods[:5]: # Only show next 5 periods
230 forecast = f"""
231 {period["name"]}:
232 Temperature: {period["temperature"]}°{period["temperatureUnit"]}
233 Wind: {period["windSpeed"]} {period["windDirection"]}
234 Forecast: {period["detailedForecast"]}
235 """
236 forecasts.append(forecast)
237 
238 return "\n---\n".join(forecasts)
239 ```
240 
241 ### Running the server
242 
243 Finally, let's initialize and run the server:
244 
245 ```python theme={null}
246 if __name__ == "__main__":
247 mcp.run(transport="stdio")
248 ```
249 
250 Your server is complete! Run `uv run weather.py` to start the MCP server, which will listen for messages from MCP hosts.
251 
252 Let's now test your server from an existing MCP host, Claude for Desktop.
253 
254 ## Testing your server with Claude for Desktop
255 
256 First, make sure you have Claude for Desktop installed. [You can install the latest version
257 here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
258 
259 We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
260 
261 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
262 
263 <CodeGroup>
264 ```bash Linux theme={null}
265 code ~/.config/Claude/claude_desktop_config.json
266 ```
267 
268 ```bash macOS theme={null}
269 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
270 ```
271 
272 ```powershell Windows theme={null}
273 code $env:AppData\Claude\claude_desktop_config.json
274 ```
275 </CodeGroup>
276 
277 You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
278 
279 In this case, we'll add our single weather server like so:
280 
281 <CodeGroup>
282 ```json macOS/Linux theme={null}
283 {
284 "mcpServers": {
285 "weather": {
286 "command": "uv",
287 "args": [
288 "--directory",
289 "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
290 "run",
291 "weather.py"
292 ]
293 }
1234 ${period.name}:
1235 Temperature: ${period.temperature}°${period.temperatureUnit}
1236 Wind: ${period.windSpeed} ${period.windDirection}
1237 ${period.shortForecast}
1238 """.trimIndent()
1239 }
1240}
1241 
1242@Serializable
1243data class PointsResponse(val properties: PointsProperties)
1244 
1245@Serializable
1246data class PointsProperties(val forecast: String? = null)
1247 
1248@Serializable
1249data class ForecastResponse(val properties: ForecastProperties)
1250 
1251@Serializable
1252data class ForecastProperties(val periods: List<ForecastPeriod> = emptyList())
1253 
1254@Serializable
1255data class ForecastPeriod(
1256 val name: String? = null,
1257 val temperature: Int? = null,
1258 val temperatureUnit: String? = null,
1259 val windSpeed: String? = null,
1260 val windDirection: String? = null,
1261 val shortForecast: String? = null,
1262)
1263 
1264@Serializable
1265data class AlertsResponse(val features: List<AlertFeature> = emptyList())
1266 
1267@Serializable
1268data class AlertFeature(val properties: AlertProperties)
1269 
1270@Serializable
1271data class AlertProperties(
1272 val event: String? = null,
1273 val areaDesc: String? = null,
1274 val severity: String? = null,
1275 val status: String? = null,
1276 val headline: String? = null,
1277)
1278```
1279 
1280### Implementing tool execution
1281 
1282The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
1283 
1284```kotlin theme={null}
1285// Register weather tools
1286 
1287server.addTool(
1288 name = "get_alerts",
1289 description = "Get weather alerts for a US state. Input is a two-letter US state code (e.g. CA, NY)",
1290 inputSchema = ToolSchema(
1291 properties = buildJsonObject {
1292 putJsonObject("state") {
1293 put("type", "string")
1294 put("description", "Two-letter US state code (e.g. CA, NY)")
1295 }
1296 },
1297 required = listOf("state"),
1298 ),
1299) { request ->
1300 val state = request.arguments?.get("state")?.jsonPrimitive?.content
1301 ?: return@addTool CallToolResult(
1302 content = listOf(TextContent("The 'state' parameter is required.")),
1303 )
1304 
1305 val alerts = httpClient.getAlerts(state)
1306 CallToolResult(content = alerts.map { TextContent(it) })
1307}
1308 
1309server.addTool(
1310 name = "get_forecast",
1311 description = "Get weather forecast for a location. Note: only US locations are supported by the NWS API.",
1312 inputSchema = ToolSchema(
1313 properties = buildJsonObject {
1314 putJsonObject("latitude") {
1315 put("type", "number")
1316 put("description", "Latitude of the location")
1317 }
1318 putJsonObject("longitude") {
1319 put("type", "number")
1320 put("description", "Longitude of the location")
1321 }
1322 },
1323 required = listOf("latitude", "longitude"),
1324 ),
1325) { request ->
1326 val latitude = request.arguments?.get("latitude")?.jsonPrimitive?.doubleOrNull
1327 val longitude = request.arguments?.get("longitude")?.jsonPrimitive?.doubleOrNull
1328 if (latitude == null || longitude == null) {
1329 return@addTool CallToolResult(
1330 content = listOf(TextContent("The 'latitude' and 'longitude' parameters are required.")),
1331 )
1332 }
1333 
1334 val forecast = httpClient.getForecast(latitude, longitude)
1335 CallToolResult(content = forecast.map { TextContent(it) })
1336}
1337```
1338 
1339### Running the server
1340 
1341Finally, implement the main function to run the server:
1342 
1343```kotlin theme={null}
1344fun main() = runMcpServer()
1345```
1346 
1347You can run the server directly during development:
1348 
1349```bash theme={null}
1350./gradlew run
1351```
1352 
1353For production use, build the shadow JAR:
1354 
1355```bash theme={null}
1356./gradlew build
1357java -jar build/libs/weather-0.1.0-all.jar
1358```
1359 
1360Let's now test your server from an existing MCP host, Claude for Desktop.
1361 
1362## Testing your server with Claude for Desktop
1363 
1364First, make sure you have Claude for Desktop installed. [You can install the latest version
1365here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
1366 
1367We'll need to configure Claude for Desktop for whichever MCP servers you want to use.
1368To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor.
1369Make sure to create the file if it doesn't exist.
1370 
1371For example, if you have [VS Code](https://code.visualstudio.com/) installed:
1372 
1373```bash Linux theme={null}
1374code ~/.config/Claude/claude_desktop_config.json
1375```
1376 
1377```bash macOS theme={null}
1378code ~/Library/Application\ Support/Claude/claude_desktop_config.json
1379```
1380 
1381```powershell Windows theme={null}
1382code $env:AppData\Claude\claude_desktop_config.json
1383```
1384 
1385You'll then add your servers in the `mcpServers` key.
1386The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
1387 
1388In this case, we'll add our single weather server like so:
1389 
1390```json macOS/Linux theme={null}
1391{
1392 "mcpServers": {
1393 "weather": {
1394 "command": "java",
1395 "args": [
1396 "-jar",
1397 "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/libs/weather-0.1.0-all.jar"
1398 ]
1399 }
1400 }
1401}
1402```
1403 
1404```json Windows theme={null}
1405{
1406 "mcpServers": {
1407 "weather": {
1408 "command": "java",
1409 "args": [
1410 "-jar",
1411 "C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\libs\\weather-0.1.0-all.jar"
1412 ]
1413 }
1414 }
1415}
1416```
1417 
1418This tells Claude for Desktop:
1419 
14201. There's an MCP server named "weather"
14212. Launch it by running `java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/libs/weather-0.1.0-all.jar`
1422 
1423Save the file, and restart **Claude for Desktop**.
1424 
1425**C#**
1426 
1427Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/csharp-sdk/tree/main/samples/QuickstartWeatherServer)
1428 
1429### Prerequisite knowledge
1430 
1431This quickstart assumes you have familiarity with:
1432 
1433* C#
1434* LLMs like Claude
1435* .NET 8 or higher
1436 
1437### Logging in MCP Servers
1438 
1439When implementing MCP servers, be careful about how you handle logging:
1440 
1441**For STDIO-based servers:** Never use `Console.WriteLine()` or `Console.Write()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
1442 
1443**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
1444 
1445### Best Practices
1446 
1447* Use a logging library that writes to stderr or files.
1448 
1449### System requirements
1450 
1451* [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) or higher installed.
1452 
1453### Set up your environment
1454 
1455First, let's install `dotnet` if you haven't already. You can download `dotnet` from [official Microsoft .NET website](https://dotnet.microsoft.com/download/). Verify your `dotnet` installation:
1456 
1457```bash theme={null}
1458dotnet --version
1459```
1460 
1461Now, let's create and set up your project:
1462 
1463```bash macOS/Linux theme={null}
1464# Create a new directory for our project
1465mkdir weather
1466cd weather
1467# Initialize a new C# project
1468dotnet new console
1469```
1470 
1471```powershell Windows theme={null}
1472# Create a new directory for our project
1473mkdir weather
1474cd weather
1475# Initialize a new C# project
1476dotnet new console
1477```
1478 
1479After running `dotnet new console`, you will be presented with a new C# project.
1480You can open the project in your favorite IDE, such as [Visual Studio](https://visualstudio.microsoft.com/) or [Rider](https://www.jetbrains.com/rider/).
1481Alternatively, you can create a C# application using the [Visual Studio project wizard](https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-console?view=vs-2022).
1482After creating the project, add NuGet package for the Model Context Protocol SDK and hosting:
1483 
1484```bash theme={null}
1485# Add the Model Context Protocol SDK NuGet package
1486dotnet add package ModelContextProtocol --prerelease
1487# Add the .NET Hosting NuGet package
1488dotnet add package Microsoft.Extensions.Hosting
1489```
1490 
1491Now let’s dive into building your server.
1492 
1493## Building your server
1494 
1495Open the `Program.cs` file in your project and replace its contents with the following code:
1496 
1497```csharp theme={null}
1498using Microsoft.Extensions.DependencyInjection;
1499using Microsoft.Extensions.Hosting;
1500using ModelContextProtocol;
1501using System.Net.Http.Headers;
1502 
1503var builder = Host.CreateEmptyApplicationBuilder(settings: null);
1504 
1505builder.Services.AddMcpServer()
1506 .WithStdioServerTransport()
1507 .WithToolsFromAssembly();
1508 
1509builder.Services.AddSingleton(_ =>
1510{
1511 var client = new HttpClient() { BaseAddress = new Uri("https://api.weather.gov") };
1512 client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("weather-tool", "1.0"));
1513 return client;
1514});
1515 
1516var app = builder.Build();
1517 
1518await app.RunAsync();
1519```
1520 
1521> [!NOTE]
1522>
1523> When creating the `ApplicationHostBuilder`, ensure you use `CreateEmptyApplicationBuilder` instead of `CreateDefaultBuilder`. This ensures that the server does not write any additional messages to the console. This is only necessary for servers using STDIO transport.
1524 
1525This code sets up a basic console application that uses the Model Context Protocol SDK to create an MCP server with standard I/O transport.
1526 
1527### Weather API helper functions
1528 
1529Create an extension class for `HttpClient` which helps simplify JSON request handling:
1530 
1531```csharp theme={null}
1532using System.Text.Json;
1533 
1534internal static class HttpClientExt
1535{
1536 public static async Task<JsonDocument> ReadJsonDocumentAsync(this HttpClient client, string requestUri)
1537 {
1538 using var response = await client.GetAsync(requestUri);
1539 response.EnsureSuccessStatusCode();
1540 return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
1541 }
1542}
1543```
1544 
1545Next, define a class with the tool execution handlers for querying and converting responses from the National Weather Service API:
1546 
1547```csharp theme={null}
1548using ModelContextProtocol.Server;
1549using System.ComponentModel;
1550using System.Globalization;
1551using System.Text.Json;
1552 
1553namespace QuickstartWeatherServer.Tools;
1554 
1555[McpServerToolType]
1556public static class WeatherTools
1557{
1558 [McpServerTool, Description("Get weather alerts for a US state code.")]
1559 public static async Task<string> GetAlerts(
1560 HttpClient client,
1561 [Description("The US state code to get alerts for.")] string state)
1562 {
1563 using var jsonDocument = await client.ReadJsonDocumentAsync($"/alerts/active/area/{state}");
1564 var jsonElement = jsonDocument.RootElement;
1565 var alerts = jsonElement.GetProperty("features").EnumerateArray();
1566 
1567 if (!alerts.Any())
1568 {
1569 return "No active alerts for this state.";
2941570 }
1571 
1572 return string.Join("\n--\n", alerts.Select(alert =>
1573 {
1574 JsonElement properties = alert.GetProperty("properties");
1575 return $"""
1576 Event: {properties.GetProperty("event").GetString()}
1577 Area: {properties.GetProperty("areaDesc").GetString()}
1578 Severity: {properties.GetProperty("severity").GetString()}
1579 Description: {properties.GetProperty("description").GetString()}
1580 Instruction: {properties.GetProperty("instruction").GetString()}
1581 """;
1582 }));
1583 }
1584 
1585 [McpServerTool, Description("Get weather forecast for a location.")]
1586 public static async Task<string> GetForecast(
1587 HttpClient client,
1588 [Description("Latitude of the location.")] double latitude,
1589 [Description("Longitude of the location.")] double longitude)
1590 {
1591 var pointUrl = string.Create(CultureInfo.InvariantCulture, $"/points/{latitude},{longitude}");
1592 using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);
1593 var forecastUrl = jsonDocument.RootElement.GetProperty("properties").GetProperty("forecast").GetString()
1594 ?? throw new Exception($"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}");
1595 
1596 using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl);
1597 var periods = forecastDocument.RootElement.GetProperty("properties").GetProperty("periods").EnumerateArray();
1598 
1599 return string.Join("\n---\n", periods.Select(period => $"""
1600 {period.GetProperty("name").GetString()}
1601 Temperature: {period.GetProperty("temperature").GetInt32()}°F
1602 Wind: {period.GetProperty("windSpeed").GetString()} {period.GetProperty("windDirection").GetString()}
1603 Forecast: {period.GetProperty("detailedForecast").GetString()}
1604 """));
1605 }
1606}
1607```
1608 
1609### Running the server
1610 
1611Finally, run the server using the following command:
1612 
1613```bash theme={null}
1614dotnet run
1615```
1616 
1617This will start the server and listen for incoming requests on standard input/output.
1618 
1619## Testing your server with Claude for Desktop
1620 
1621First, make sure you have Claude for Desktop installed. [You can install the latest version
1622here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
1623We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
1624For example, if you have [VS Code](https://code.visualstudio.com/) installed:
1625 
1626```bash Linux theme={null}
1627code ~/.config/Claude/claude_desktop_config.json
1628```
1629 
1630```bash macOS theme={null}
1631code ~/Library/Application\ Support/Claude/claude_desktop_config.json
1632```
1633 
1634```powershell Windows theme={null}
1635code $env:AppData\Claude\claude_desktop_config.json
1636```
1637 
1638You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
1639In this case, we'll add our single weather server like so:
1640 
1641```json macOS/Linux theme={null}
1642{
1643 "mcpServers": {
1644 "weather": {
1645 "command": "dotnet",
1646 "args": ["run", "--project", "/ABSOLUTE/PATH/TO/PROJECT", "--no-build"]
1647 }
1648 }
1649}
1650```
1651 
1652```json Windows theme={null}
1653{
1654 "mcpServers": {
1655 "weather": {
1656 "command": "dotnet",
1657 "args": [
1658 "run",
1659 "--project",
1660 "C:\\ABSOLUTE\\PATH\\TO\\PROJECT",
1661 "--no-build"
1662 ]
1663 }
1664 }
1665}
1666```
1667 
1668This tells Claude for Desktop:
1669 
16701. There's an MCP server named "weather"
16712. Launch it by running `dotnet run /ABSOLUTE/PATH/TO/PROJECT`
1672 Save the file, and restart **Claude for Desktop**.
1673 
1674**Ruby**
1675 
1676Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-ruby)
1677 
1678### Prerequisite knowledge
1679 
1680This quickstart assumes you have familiarity with:
1681 
1682* Ruby
1683* LLMs like Claude
1684 
1685### Logging in MCP Servers
1686 
1687When implementing MCP servers, be careful about how you handle logging:
1688 
1689**For STDIO-based servers:** Never use `puts` or `print`, as they write to standard output (stdout) by default. Writing to stdout will corrupt the JSON-RPC messages and break your server.
1690 
1691**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
1692 
1693### Best Practices
1694 
1695* Use a logging library that writes to stderr or files.
1696 
1697### Quick Examples
1698 
1699```ruby theme={null}
1700# ❌ Bad (STDIO)
1701puts "Processing request"
1702 
1703# ✅ Good (STDIO)
1704require "logger"
1705logger = Logger.new($stderr)
1706logger.info("Processing request")
1707```
1708 
1709### System requirements
1710 
1711* Ruby 2.7 or higher installed.
1712 
1713### Set up your environment
1714 
1715First, let's make sure you have Ruby installed. You can check by running:
1716 
1717```bash theme={null}
1718ruby --version
1719```
1720 
1721Now, let's create and set up our project:
1722 
1723```bash macOS/Linux theme={null}
1724# Create a new directory for our project
1725mkdir weather
1726cd weather
1727 
1728# Create a Gemfile
1729bundle init
1730 
1731# Add the MCP SDK dependency
1732bundle add mcp
1733 
1734# Create our server file
1735touch weather.rb
1736```
1737 
1738```powershell Windows theme={null}
1739# Create a new directory for our project
1740mkdir weather
1741cd weather
1742 
1743# Create a Gemfile
1744bundle init
1745 
1746# Add the MCP SDK dependency
1747bundle add mcp
1748 
1749# Create our server file
1750new-item weather.rb
1751```
1752 
1753Now let's dive into building your server.
1754 
1755## Building your server
1756 
1757### Importing packages and setting up constants
1758 
1759Open `weather.rb` and add these requires and constants at the top:
1760 
1761```ruby theme={null}
1762require "json"
1763require "mcp"
1764require "net/http"
1765require "uri"
1766 
1767NWS_API_BASE = "https://api.weather.gov"
1768USER_AGENT = "weather-app/1.0"
1769```
1770 
1771The `mcp` gem provides the Model Context Protocol SDK for Ruby, with classes for server implementation and stdio transport.
1772 
1773### Helper methods
1774 
1775Next, let's add helper methods for querying and formatting data from the National Weather Service API:
1776 
1777```ruby theme={null}
1778module HelperMethods
1779 def make_nws_request(url)
1780 uri = URI(url)
1781 request = Net::HTTP::Get.new(uri)
1782 request["User-Agent"] = USER_AGENT
1783 request["Accept"] = "application/geo+json"
1784 
1785 response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
1786 http.request(request)
1787 end
1788 
1789 raise "HTTP #{response.code}: #{response.message}" unless response.is_a?(Net::HTTPSuccess)
1790 
1791 JSON.parse(response.body)
1792 end
1793 
1794 def format_alert(feature)
1795 properties = feature["properties"]
1796 
1797 <<~ALERT
1798 Event: #{properties["event"] || "Unknown"}
1799 Area: #{properties["areaDesc"] || "Unknown"}
1800 Severity: #{properties["severity"] || "Unknown"}
1801 Description: #{properties["description"] || "No description available"}
1802 Instructions: #{properties["instruction"] || "No specific instructions provided"}
1803 ALERT
1804 end
1805end
1806```
1807 
1808### Implementing tool execution
1809 
1810Now let's define our tool classes. Each tool subclasses `MCP::Tool` and implements the tool logic:
1811 
1812```ruby theme={null}
1813class GetAlerts < MCP::Tool
1814 extend HelperMethods
1815 
1816 tool_name "get_alerts"
1817 description "Get weather alerts for a US state"
1818 input_schema(
1819 properties: {
1820 state: {
1821 type: "string",
1822 description: "Two-letter US state code (e.g. CA, NY)"
2951823 }
296 ```
297 
298 ```json Windows theme={null}
299 {
300 "mcpServers": {
301 "weather": {
302 "command": "uv",
303 "args": [
304 "--directory",
305 "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather",
306 "run",
307 "weather.py"
308 ]
309 }
310 }
1824 },
1825 required: ["state"]
1826 )
1827 
1828 def self.call(state:)
1829 url = "#{NWS_API_BASE}/alerts/active/area/#{state.upcase}"
1830 data = make_nws_request(url)
1831 
1832 if data["features"].empty?
1833 return MCP::Tool::Response.new([{
1834 type: "text",
1835 text: "No active alerts for this state."
1836 }])
1837 end
1838 
1839 alerts = data["features"].map { |feature| format_alert(feature) }
1840 MCP::Tool::Response.new([{
1841 type: "text",
1842 text: alerts.join("\n---\n")
1843 }])
1844 end
1845end
1846 
1847class GetForecast < MCP::Tool
1848 extend HelperMethods
1849 
1850 tool_name "get_forecast"
1851 description "Get weather forecast for a location"
1852 input_schema(
1853 properties: {
1854 latitude: {
1855 type: "number",
1856 description: "Latitude of the location"
1857 },
1858 longitude: {
1859 type: "number",
1860 description: "Longitude of the location"
3111861 }
312 ```
313 </CodeGroup>
314 
315 <Warning>
316 You may need to put the full path to the `uv` executable in the `command` field. You can get this by running `which uv` on macOS/Linux or `where uv` on Windows.
317 </Warning>
318 
319 <Note>
320 Make sure you pass in the absolute path to your server. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path.
321 </Note>
322 
323 This tells Claude for Desktop:
324 
325 1. There's an MCP server named "weather"
326 2. To launch it by running `uv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather.py`
327 
328 Save the file, and restart **Claude for Desktop**.
329 </Tab>
330 
331 <Tab title="TypeScript">
332 Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript)
333 
334 ### Prerequisite knowledge
335 
336 This quickstart assumes you have familiarity with:
337 
338 * TypeScript
339 * LLMs like Claude
340 
341 ### Logging in MCP Servers
342 
343 When implementing MCP servers, be careful about how you handle logging:
344 
345 **For STDIO-based servers:** Never use `console.log()`, as it writes to standard output (stdout) by default. Writing to stdout will corrupt the JSON-RPC messages and break your server.
346 
347 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
348 
349 ### Best Practices
350 
351 * Use `console.error()` which writes to stderr, or use a logging library that writes to stderr or files.
352 
353 ### Quick Examples
354 
355 ```javascript theme={null}
356 // ❌ Bad (STDIO)
357 console.log("Server started");
358 
359 // ✅ Good (STDIO)
360 console.error("Server started"); // stderr is safe
361 ```
362 
363 ### System requirements
364 
365 For TypeScript, make sure you have the latest version of Node installed.
366 
367 ### Set up your environment
368 
369 First, let's install Node.js and npm if you haven't already. You can download them from [nodejs.org](https://nodejs.org/).
370 Verify your Node.js installation:
371 
372 ```bash theme={null}
373 node --version
374 npm --version
375 ```
376 
377 For this tutorial, you'll need Node.js version 20 or higher.
378 
379 Now, let's create and set up our project:
380 
381 <CodeGroup>
382 ```bash macOS/Linux theme={null}
383 # Create a new directory for our project
384 mkdir weather
385 cd weather
386 
387 # Initialize a new npm project
388 npm init -y
389 
390 # Install dependencies
391 npm install @modelcontextprotocol/server zod
392 npm install -D @types/node typescript
393 
394 # Create our files
395 mkdir src
396 touch src/index.ts
397 ```
398 
399 ```powershell Windows theme={null}
400 # Create a new directory for our project
401 md weather
402 cd weather
403 
404 # Initialize a new npm project
405 npm init -y
406 
407 # Install dependencies
408 npm install @modelcontextprotocol/server zod
409 npm install -D @types/node typescript
410 
411 # Create our files
412 md src
413 new-item src\index.ts
414 ```
415 </CodeGroup>
416 
417 Update your package.json to add type: "module" and a build script:
418 
419 ```json package.json theme={null}
420 {
421 "type": "module",
422 "bin": {
423 "weather": "./build/index.js"
424 },
425 "scripts": {
426 "build": "tsc && chmod 755 build/index.js"
427 },
428 "files": ["build"]
1862 },
1863 required: ["latitude", "longitude"]
1864 )
1865 
1866 def self.call(latitude:, longitude:)
1867 # First get the forecast grid endpoint.
1868 points_url = "#{NWS_API_BASE}/points/#{latitude},#{longitude}"
1869 points_data = make_nws_request(points_url)
1870 
1871 # Get the forecast URL from the points response.
1872 forecast_url = points_data["properties"]["forecast"]
1873 forecast_data = make_nws_request(forecast_url)
1874 
1875 # Format the periods into a readable forecast.
1876 periods = forecast_data["properties"]["periods"]
1877 forecasts = periods.first(5).map do |period|
1878 <<~FORECAST
1879 #{period["name"]}:
1880 Temperature: #{period["temperature"]}°#{period["temperatureUnit"]}
1881 Wind: #{period["windSpeed"]} #{period["windDirection"]}
1882 Forecast: #{period["detailedForecast"]}
1883 FORECAST
1884 end
1885 
1886 MCP::Tool::Response.new([{
1887 type: "text",
1888 text: forecasts.join("\n---\n")
1889 }])
1890 end
1891end
1892```
1893 
1894### Running the server
1895 
1896Finally, initialize and run the server:
1897 
1898```ruby theme={null}
1899server = MCP::Server.new(
1900 name: "weather",
1901 version: "1.0.0",
1902 tools: [GetAlerts, GetForecast]
1903)
1904 
1905transport = MCP::Server::Transports::StdioTransport.new(server)
1906transport.open
1907```
1908 
1909Your server is complete! Run `bundle exec ruby weather.rb` to start the MCP server, which will listen for messages from MCP hosts.
1910 
1911Let's now test your server from an existing MCP host, Claude for Desktop.
1912 
1913## Testing your server with Claude for Desktop
1914 
1915First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
1916 
1917We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
1918 
1919For example, if you have [VS Code](https://code.visualstudio.com/) installed:
1920 
1921```bash Linux theme={null}
1922code ~/.config/Claude/claude_desktop_config.json
1923```
1924 
1925```bash macOS theme={null}
1926code ~/Library/Application\ Support/Claude/claude_desktop_config.json
1927```
1928 
1929```powershell Windows theme={null}
1930code $env:AppData\Claude\claude_desktop_config.json
1931```
1932 
1933You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
1934 
1935In this case, we'll add our single weather server like so:
1936 
1937```json macOS/Linux theme={null}
1938{
1939 "mcpServers": {
1940 "weather": {
1941 "command": "bundle",
1942 "args": ["exec", "ruby", "weather.rb"],
1943 "cwd": "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather"
4291944 }
430 ```
431 
432 Create a `tsconfig.json` in the root of your project:
433 
434 ```json tsconfig.json theme={null}
435 {
436 "compilerOptions": {
437 "target": "ES2022",
438 "module": "Node16",
439 "moduleResolution": "Node16",
440 "types": ["node"],
441 "outDir": "./build",
442 "rootDir": "./src",
443 "strict": true,
444 "esModuleInterop": true,
445 "skipLibCheck": true,
446 "forceConsistentCasingInFileNames": true
447 },
448 "include": ["src/**/*"],
449 "exclude": ["node_modules"]
1945 }
1946}
1947```
1948 
1949```json Windows theme={null}
1950{
1951 "mcpServers": {
1952 "weather": {
1953 "command": "bundle",
1954 "args": ["exec", "ruby", "weather.rb"],
1955 "cwd": "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather"
4501956 }
451 ```
452 
453 Now let's dive into building your server.
454 
455 ## Building your server
456 
457 ### Importing packages and setting up constants
458 
459 Add these to the top of your `src/index.ts`:
460 
461 ```typescript theme={null}
462 import { McpServer } from "@modelcontextprotocol/server";
463 import { serveStdio } from "@modelcontextprotocol/server/stdio";
464 import { z } from "zod";
465 
466 const NWS_API_BASE = "https://api.weather.gov";
467 const USER_AGENT = "weather-app/1.0";
468 ```
469 
470 ### Helper functions
471 
472 Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
473 
474 ```typescript theme={null}
475 // Helper function for making NWS API requests
476 async function makeNWSRequest<T>(url: string): Promise<T | null> {
477 const headers = {
478 "User-Agent": USER_AGENT,
479 Accept: "application/geo+json",
480 };
481 
482 try {
483 const response = await fetch(url, { headers });
484 if (!response.ok) {
485 throw new Error(`HTTP error! status: ${response.status}`);
486 }
487 return (await response.json()) as T;
488 } catch (error) {
489 console.error("Error making NWS request:", error);
490 return null;
491 }
492 }
493 
494 interface AlertFeature {
495 properties: {
496 event?: string;
497 areaDesc?: string;
498 severity?: string;
499 status?: string;
500 headline?: string;
501 };
502 }
503 
504 // Format alert data
505 function formatAlert(feature: AlertFeature): string {
506 const props = feature.properties;
507 return [
508 `Event: ${props.event || "Unknown"}`,
509 `Area: ${props.areaDesc || "Unknown"}`,
510 `Severity: ${props.severity || "Unknown"}`,
511 `Status: ${props.status || "Unknown"}`,
512 `Headline: ${props.headline || "No headline"}`,
513 "---",
514 ].join("\n");
515 }
516 
517 interface ForecastPeriod {
518 name?: string;
519 temperature?: number;
520 temperatureUnit?: string;
521 windSpeed?: string;
522 windDirection?: string;
523 shortForecast?: string;
524 }
525 
526 interface AlertsResponse {
527 features: AlertFeature[];
528 }
529 
530 interface PointsResponse {
531 properties: {
532 forecast?: string;
533 };
534 }
535 
536 interface ForecastResponse {
537 properties: {
538 periods: ForecastPeriod[];
539 };
540 }
541 ```
542 
543 ### Implementing tool execution
544 
545 The tool execution handler is responsible for actually executing the logic of each tool. Let's add it, inside a `createServer()` function that builds the server instance and registers both tools on it:
546 
547 ```typescript theme={null}
548 // Build a server instance and register its tools. serveStdio calls this
549 // whenever it needs an instance, so every call must return a fresh one.
550 function createServer() {
551 const server = new McpServer({
552 name: "weather",
553 version: "1.0.0",
554 });
555 
556 server.registerTool(
557 "get_alerts",
558 {
559 description: "Get weather alerts for a state",
560 inputSchema: z.object({
561 state: z
562 .string()
563 .length(2)
564 .describe("Two-letter state code (e.g. CA, NY)"),
565 }),
566 },
567 async ({ state }) => {
568 const stateCode = state.toUpperCase();
569 const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`;
570 const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl);
571 
572 if (!alertsData) {
573 return {
574 content: [
575 {
576 type: "text",
577 text: "Failed to retrieve alerts data",
578 },
579 ],
580 };
581 }
582 
583 const features = alertsData.features || [];
584 if (!features.length) {
585 return {
586 content: [
587 {
588 type: "text",
589 text: `No active alerts for ${stateCode}`,
590 },
591 ],
592 };
593 }
594 
595 const formattedAlerts = features.map(formatAlert);
596 const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join("\n")}`;
597 
598 return {
599 content: [
600 {
601 type: "text",
602 text: alertsText,
603 },
604 ],
605 };
606 },
607 );
608 
609 server.registerTool(
610 "get_forecast",
611 {
612 description: "Get weather forecast for a location",
613 inputSchema: z.object({
614 latitude: z
615 .number()
616 .min(-90)
617 .max(90)
618 .describe("Latitude of the location"),
619 longitude: z
620 .number()
621 .min(-180)
622 .max(180)
623 .describe("Longitude of the location"),
624 }),
625 },
626 async ({ latitude, longitude }) => {
627 // Get grid point data
628 const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`;
629 const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl);
630 
631 if (!pointsData) {
632 return {
633 content: [
634 {
635 type: "text",
636 text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`,
637 },
638 ],
639 };
640 }
641 
642 const forecastUrl = pointsData.properties?.forecast;
643 if (!forecastUrl) {
644 return {
645 content: [
646 {
647 type: "text",
648 text: "Failed to get forecast URL from grid point data",
649 },
650 ],
651 };
652 }
653 
654 // Get forecast data
655 const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl);
656 if (!forecastData) {
657 return {
658 content: [
659 {
660 type: "text",
661 text: "Failed to retrieve forecast data",
662 },
663 ],
664 };
665 }
666 
667 const periods = forecastData.properties?.periods || [];
668 if (periods.length === 0) {
669 return {
670 content: [
671 {
672 type: "text",
673 text: "No forecast periods available",
674 },
675 ],
676 };
677 }
678 
679 // Format forecast periods
680 const formattedForecast = periods.map((period: ForecastPeriod) =>
681 [
682 `${period.name || "Unknown"}:`,
683 `Temperature: ${period.temperature || "Unknown"}°${period.temperatureUnit || "F"}`,
684 `Wind: ${period.windSpeed || "Unknown"} ${period.windDirection || ""}`,
685 `${period.shortForecast || "No forecast available"}`,
686 "---",
687 ].join("\n"),
688 );
689 
690 const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join("\n")}`;
691 
692 return {
693 content: [
694 {
695 type: "text",
696 text: forecastText,
697 },
698 ],
699 };
700 },
701 );
702 
703 return server;
704 }
705 ```
706 
707 ### Running the server
708 
709 Finally, serve the server over stdio:
710 
711 ```typescript theme={null}
712 serveStdio(createServer, {
713 onerror: (error) => console.error("Weather MCP Server error:", error),
714 });
715 console.error("Weather MCP Server running on stdio");
716 ```
717 
718 `serveStdio` negotiates the protocol revision with each client, so the same server answers both 2026-07-28 clients and clients that still open with the 2025-era `initialize` handshake. It calls `createServer()` whenever it needs an instance, including once for a `server/discover` probe that is discarded if the client falls back to `initialize`, which is why the factory returns a new `McpServer` on every call. Wiring the server by hand with `server.connect(new StdioServerTransport())` still compiles, but a server started that way only serves 2025-era clients.
719 
720 Make sure to run `npm run build` to build your server! This is a very important step in getting your server to connect.
721 
722 To check that the server answers 2026-07-28 clients, list its tools with the [Inspector CLI](/docs/2026-07-28/tools/inspector/cli) in the `modern` [protocol era](/docs/2026-07-28/tools/inspector/protocol-eras):
723 
724 ```bash theme={null}
725 npx @modelcontextprotocol/inspector --cli node build/index.js --protocol-era modern --method tools/list
726 ```
727 
728 The Inspector defaults to the `legacy` era, which only exercises the 2025-era handshake, so run the same command once more with `--protocol-era legacy`. Both runs list `get_alerts` and `get_forecast`.
729 
730 Let's now test your server from an existing MCP host, Claude for Desktop.
731 
732 ## Testing your server with Claude for Desktop
733 
734 First, make sure you have Claude for Desktop installed. [You can install the latest version
735 here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
736 
737 We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
738 
739 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
740 
741 <CodeGroup>
742 ```bash Linux theme={null}
743 code ~/.config/Claude/claude_desktop_config.json
744 ```
745 
746 ```bash macOS theme={null}
747 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
748 ```
749 
750 ```powershell Windows theme={null}
751 code $env:AppData\Claude\claude_desktop_config.json
752 ```
753 </CodeGroup>
754 
755 You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
756 
757 In this case, we'll add our single weather server like so:
758 
759 <CodeGroup>
760 ```json macOS/Linux theme={null}
761 {
762 "mcpServers": {
763 "weather": {
764 "command": "node",
765 "args": ["/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js"]
766 }
767 }
768 }
769 ```
770 
771 ```json Windows theme={null}
772 {
773 "mcpServers": {
774 "weather": {
775 "command": "node",
776 "args": ["C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\index.js"]
777 }
778 }
779 }
780 ```
781 </CodeGroup>
782 
783 This tells Claude for Desktop:
784 
785 1. There's an MCP server named "weather"
786 2. Launch it by running `node /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js`
787 
788 Save the file, and restart **Claude for Desktop**.
789 </Tab>
790 
791 <Tab title="Java">
792 <Note>
793 This is a quickstart demo based on Spring AI MCP auto-configuration and boot starters.
794 To learn how to create sync and async MCP Servers, manually, consult the [Java SDK Server](https://java.sdk.modelcontextprotocol.io/) documentation.
795 </Note>
796 
797 Let's get started with building our weather server!
798 [You can find the complete code for what we'll be building here.](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-stdio-server)
799 
800 For more information, see the [MCP Server Boot Starter](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html) reference documentation.
801 For manual MCP Server implementation, refer to the [MCP Server Java SDK documentation](https://java.sdk.modelcontextprotocol.io/).
802 
803 ### Logging in MCP Servers
804 
805 When implementing MCP servers, be careful about how you handle logging:
806 
807 **For STDIO-based servers:** Never use `System.out.println()` or `System.out.print()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
808 
809 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
810 
811 ### Best Practices
812 
813 * Use a logging library that writes to stderr or files.
814 * Ensure any configured logging library will not write to stdout.
815 
816 ### System requirements
817 
818 * Java 17 or higher installed.
819 * [Spring Boot 3.3.x](https://docs.spring.io/spring-boot/installing.html) or higher
820 
821 ### Set up your environment
822 
823 Use the [Spring Initializer](https://start.spring.io/) to bootstrap the project.
824 
825 You will need to add the following dependencies:
826 
827 <CodeGroup>
828 ```xml Maven theme={null}
829 <dependencies>
830 <dependency>
831 <groupId>org.springframework.ai</groupId>
832 <artifactId>spring-ai-starter-mcp-server</artifactId>
833 </dependency>
834 
835 <dependency>
836 <groupId>org.springframework</groupId>
837 <artifactId>spring-web</artifactId>
838 </dependency>
839 </dependencies>
840 ```
841 
842 ```groovy Gradle theme={null}
843 dependencies {
844 implementation platform("org.springframework.ai:spring-ai-starter-mcp-server")
845 implementation platform("org.springframework:spring-web")
846 }
847 ```
848 </CodeGroup>
849 
850 Then configure your application by setting the application properties:
851 
852 <CodeGroup>
853 ```bash application.properties theme={null}
854 spring.main.bannerMode=off
855 logging.pattern.console=
856 ```
857 
858 ```yaml application.yml theme={null}
859 logging:
860 pattern:
861 console:
862 spring:
863 main:
864 banner-mode: off
865 ```
866 </CodeGroup>
867 
868 The [Server Configuration Properties](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html#_configuration_properties) documents all available properties.
869 
870 Now let's dive into building your server.
871 
872 ## Building your server
873 
874 ### Weather Service
875 
876 Let's implement a [WeatherService.java](https://github.com/spring-projects/spring-ai-examples/blob/main/model-context-protocol/weather/starter-stdio-server/src/main/java/org/springframework/ai/mcp/sample/server/WeatherService.java) that uses a REST client to query the data from the National Weather Service API:
877 
878 ```java theme={null}
879 @Service
880 public class WeatherService {
881 
882 private final RestClient restClient;
883 
884 public WeatherService() {
885 this.restClient = RestClient.builder()
886 .baseUrl("https://api.weather.gov")
887 .defaultHeader("Accept", "application/geo+json")
888 .defaultHeader("User-Agent", "WeatherApiClient/1.0 ([email protected])")
889 .build();
890 }
891 
892 @Tool(description = "Get weather forecast for a specific latitude/longitude")
893 public String getWeatherForecastByLocation(
894 double latitude, // Latitude coordinate
895 double longitude // Longitude coordinate
896 ) {
897 // Returns detailed forecast including:
898 // - Temperature and unit
899 // - Wind speed and direction
900 // - Detailed forecast description
901 }
902 
903 @Tool(description = "Get weather alerts for a US state")
904 public String getAlerts(
905 @ToolParam(description = "Two-letter US state code (e.g. CA, NY)") String state
906 ) {
907 // Returns active alerts including:
908 // - Event type
909 // - Affected area
910 // - Severity
911 // - Description
912 // - Safety instructions
913 }
914 
915 // ......
916 }
917 ```
918 
919 The `@Service` annotation will auto-register the service in your application context.
920 The Spring AI `@Tool` annotation makes it easy to create and maintain MCP tools.
921 
922 The auto-configuration will automatically register these tools with the MCP server.
923 
924 ### Create your Boot Application
925 
926 ```java theme={null}
927 @SpringBootApplication
928 public class McpServerApplication {
929 
930 public static void main(String[] args) {
931 SpringApplication.run(McpServerApplication.class, args);
932 }
933 
934 @Bean
935 public ToolCallbackProvider weatherTools(WeatherService weatherService) {
936 return MethodToolCallbackProvider.builder().toolObjects(weatherService).build();
937 }
938 }
939 ```
940 
941 Uses the `MethodToolCallbackProvider` utils to convert the `@Tools` into actionable callbacks used by the MCP server.
942 
943 ### Running the server
944 
945 Finally, let's build the server:
946 
947 ```bash theme={null}
948 ./mvnw clean install
949 ```
950 
951 This will generate an `mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar` file within the `target` folder.
952 
953 Let's now test your server from an existing MCP host, Claude for Desktop.
954 
955 ## Testing your server with Claude for Desktop
956 
957 First, make sure you have Claude for Desktop installed.
958 [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
959 
960 We'll need to configure Claude for Desktop for whichever MCP servers you want to use.
961 To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor.
962 Make sure to create the file if it doesn't exist.
963 
964 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
965 
966 <CodeGroup>
967 ```bash Linux theme={null}
968 code ~/.config/Claude/claude_desktop_config.json
969 ```
970 
971 ```bash macOS theme={null}
972 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
973 ```
974 
975 ```powershell Windows theme={null}
976 code $env:AppData\Claude\claude_desktop_config.json
977 ```
978 </CodeGroup>
979 
980 You'll then add your servers in the `mcpServers` key.
981 The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
982 
983 In this case, we'll add our single weather server like so:
984 
985 <CodeGroup>
986 ```json macOS/Linux theme={null}
987 {
988 "mcpServers": {
989 "spring-ai-mcp-weather": {
990 "command": "java",
991 "args": [
992 "-Dspring.ai.mcp.server.stdio=true",
993 "-jar",
994 "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
995 ]
996 }
997 }
998 }
999 ```
1000 
1001 ```json Windows theme={null}
1002 {
1003 "mcpServers": {
1004 "spring-ai-mcp-weather": {
1005 "command": "java",
1006 "args": [
1007 "-Dspring.ai.mcp.server.transport=STDIO",
1008 "-jar",
1009 "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
1010 ]
1011 }
1012 }
1013 }
1014 ```
1015 </CodeGroup>
1016 
1017 <Note>
1018 Make sure you pass in the absolute path to your server.
1019 </Note>
1020 
1021 This tells Claude for Desktop:
1022 
1023 1. There's an MCP server named "my-weather-server"
1024 2. To launch it by running `java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar`
1025 
1026 Save the file, and restart **Claude for Desktop**.
1027 
1028 ## Testing your server with Java client
1029 
1030 ### Create an MCP Client manually
1031 
1032 Use the `McpClient` to connect to the server:
1033 
1034 ```java theme={null}
1035 var stdioParams = ServerParameters.builder("java")
1036 .args("-jar", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar")
1037 .build();
1038 
1039 var stdioTransport = new StdioClientTransport(stdioParams);
1040 
1041 var mcpClient = McpClient.sync(stdioTransport).build();
1042 
1043 mcpClient.initialize();
1044 
1045 ListToolsResult toolsList = mcpClient.listTools();
1046 
1047 CallToolResult weather = mcpClient.callTool(
1048 new CallToolRequest("getWeatherForecastByLocation",
1049 Map.of("latitude", "47.6062", "longitude", "-122.3321")));
1050 
1051 CallToolResult alert = mcpClient.callTool(
1052 new CallToolRequest("getAlerts", Map.of("state", "NY")));
1053 
1054 mcpClient.closeGracefully();
1055 ```
1056 
1057 ### Use MCP Client Boot Starter
1058 
1059 Create a new boot starter application using the `spring-ai-starter-mcp-client` dependency:
1060 
1061 ```xml theme={null}
1062 <dependency>
1063 <groupId>org.springframework.ai</groupId>
1064 <artifactId>spring-ai-starter-mcp-client</artifactId>
1065 </dependency>
1066 ```
1067 
1068 and set the `spring.ai.mcp.client.stdio.servers-configuration` property to point to your `claude_desktop_config.json`.
1069 You can reuse the existing Anthropic Desktop configuration:
1070 
1071 ```properties theme={null}
1072 spring.ai.mcp.client.stdio.servers-configuration=file:PATH/TO/claude_desktop_config.json
1073 ```
1074 
1075 When you start your client application, the auto-configuration will automatically create MCP clients from the claude\_desktop\_config.json.
1076 
1077 For more information, see the [MCP Client Boot Starters](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-client-boot-starter-docs.html) reference documentation.
1078 
1079 ## More Java MCP Server examples
1080 
1081 The [starter-webflux-server](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-webflux-server) demonstrates how to create an HTTP-based MCP server with the WebFlux starter.
1082 Set the `spring.ai.mcp.server.protocol=STREAMABLE` property to serve it over Streamable HTTP.
1083 It showcases how to define and register MCP Tools, Resources, and Prompts, using the Spring Boot's auto-configuration capabilities.
1084 </Tab>
1085 
1086 <Tab title="Kotlin">
1087 Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/weather-stdio-server)
1088 
1089 ### Prerequisite knowledge
1090 
1091 This quickstart assumes you have familiarity with:
1092 
1093 * Kotlin
1094 * LLMs like Claude
1095 
1096 ### Logging in MCP Servers
1097 
1098 When implementing MCP servers, be careful about how you handle logging:
1099 
1100 **For STDIO-based servers:** Never use `println()`, as it writes to standard output (stdout) by default. Writing to stdout will corrupt the JSON-RPC messages and break your server.
1101 
1102 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
1103 
1104 ### Best Practices
1105 
1106 * Use a logging library that writes to stderr or files.
1107 
1108 ### System requirements
1109 
1110 * JDK 11 or higher installed.
1111 
1112 ### Set up your environment
1113 
1114 First, let's install `java` and `gradle` if you haven't already.
1115 You can download `java` from [official Oracle JDK website](https://www.oracle.com/java/technologies/downloads/).
1116 Verify your `java` installation:
1117 
1118 ```bash theme={null}
1119 java --version
1120 ```
1121 
1122 Now, let's create and set up your project:
1123 
1124 <CodeGroup>
1125 ```bash macOS/Linux theme={null}
1126 # Create a new directory for our project
1127 mkdir weather
1128 cd weather
1129 
1130 # Initialize a new kotlin project
1131 gradle init
1132 ```
1133 
1134 ```powershell Windows theme={null}
1135 # Create a new directory for our project
1136 md weather
1137 cd weather
1138 
1139 # Initialize a new kotlin project
1140 gradle init
1141 ```
1142 </CodeGroup>
1143 
1144 After running `gradle init`, select **Application** as the project type, **Kotlin** as the programming language.
1145 
1146 Alternatively, you can create a Kotlin application using the [IntelliJ IDEA project wizard](https://kotlinlang.org/docs/jvm-get-started.html).
1147 
1148 After creating the project, replace the contents of your `build.gradle.kts` with:
1149 
1150 ```kotlin build.gradle.kts theme={null}
1151 // Check latest versions at https://github.com/modelcontextprotocol/kotlin-sdk/releases
1152 val mcpVersion = "0.9.0"
1153 val ktorVersion = "3.2.3"
1154 val slf4jVersion = "2.0.17"
1155 
1156 plugins {
1157 kotlin("jvm") version "2.3.20"
1158 kotlin("plugin.serialization") version "2.3.20"
1159 id("com.gradleup.shadow") version "8.3.9"
1160 application
1161 }
1162 
1163 application {
1164 mainClass.set("MainKt")
1165 }
1166 
1167 dependencies {
1168 implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion")
1169 implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion")
1170 implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")
1171 implementation("io.ktor:ktor-client-cio:$ktorVersion")
1172 implementation("org.slf4j:slf4j-simple:$slf4jVersion")
1173 }
1174 ```
1175 
1176 Verify that everything is set up correctly:
1177 
1178 ```bash theme={null}
1179 ./gradlew build
1180 ```
1181 
1182 Now let's dive into building your server.
1183 
1184 ## Building your server
1185 
1186 ### Setting up the instance
1187 
1188 Add a server initialization function:
1189 
1190 ```kotlin theme={null}
1191 fun runMcpServer() {
1192 val server = Server(
1193 Implementation(
1194 name = "weather",
1195 version = "1.0.0",
1196 ),
1197 ServerOptions(
1198 capabilities = ServerCapabilities(tools = ServerCapabilities.Tools(listChanged = true)),
1199 ),
1200 )
1201 
1202 // register tools on server here
1203 
1204 val transport = StdioServerTransport(
1205 System.`in`.asInput(),
1206 System.out.asSink().buffered(),
1207 )
1208 
1209 runBlocking {
1210 val session = server.createSession(transport)
1211 val done = Job()
1212 session.onClose {
1213 done.complete()
1214 }
1215 done.join()
1957 }
1958}
1959```
1960 
1961> [!NOTE]
1962>
1963> Make sure you pass in the absolute path to your project directory in the `cwd` field. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt from your project directory. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path.
1964 
1965This tells Claude for Desktop:
1966 
19671. There's an MCP server named "weather"
19682. Launch it by running `bundle exec ruby weather.rb` in the specified directory
1969 
1970Save the file, and restart **Claude for Desktop**.
1971 
1972**Rust**
1973 
1974Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-rust)
1975 
1976### Prerequisite knowledge
1977 
1978This quickstart assumes you have familiarity with:
1979 
1980* Rust programming language
1981* Async/await in Rust
1982* LLMs like Claude
1983 
1984### Logging in MCP Servers
1985 
1986When implementing MCP servers, be careful about how you handle logging:
1987 
1988**For STDIO-based servers:** Never use `println!()` or `print!()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
1989 
1990**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
1991 
1992### Best Practices
1993 
1994* Use a logging library that writes to stderr or files, such as `tracing` or `log` in Rust.
1995* Configure your logging framework to avoid stdout output.
1996 
1997### Quick Examples
1998 
1999```rust theme={null}
2000// ❌ Bad (STDIO)
2001println!("Processing request");
2002 
2003// ✅ Good (STDIO)
2004eprintln!("Processing request"); // writes to stderr
2005```
2006 
2007### System requirements
2008 
2009* Rust 1.70 or higher installed.
2010* Cargo (comes with Rust installation).
2011 
2012### Set up your environment
2013 
2014First, let's install Rust if you haven't already. You can install Rust from [rust-lang.org](https://www.rust-lang.org/tools/install):
2015 
2016```bash macOS/Linux theme={null}
2017curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
2018```
2019 
2020```powershell Windows theme={null}
2021# Download and run rustup-init.exe from https://rustup.rs/
2022```
2023 
2024Verify your Rust installation:
2025 
2026```bash theme={null}
2027rustc --version
2028cargo --version
2029```
2030 
2031Now, let's create and set up our project:
2032 
2033```bash macOS/Linux theme={null}
2034# Create a new Rust project
2035cargo new weather
2036cd weather
2037```
2038 
2039```powershell Windows theme={null}
2040# Create a new Rust project
2041cargo new weather
2042cd weather
2043```
2044 
2045Update your `Cargo.toml` to add the required dependencies:
2046 
2047```toml Cargo.toml theme={null}
2048[package]
2049name = "weather"
2050version = "0.1.0"
2051edition = "2024"
2052 
2053[dependencies]
2054rmcp = { version = "0.3", features = ["server", "macros", "transport-io"] }
2055tokio = { version = "1.46", features = ["full"] }
2056reqwest = { version = "0.12", features = ["json"] }
2057serde = { version = "1.0", features = ["derive"] }
2058serde_json = "1.0"
2059anyhow = "1.0"
2060tracing = "0.1"
2061tracing-subscriber = { version = "0.3", features = ["env-filter", "std", "fmt"] }
2062```
2063 
2064Now let's dive into building your server.
2065 
2066## Building your server
2067 
2068### Importing packages and constants
2069 
2070Open `src/main.rs` and add these imports and constants at the top:
2071 
2072```rust theme={null}
2073use anyhow::Result;
2074use rmcp::{
2075 ServerHandler, ServiceExt,
2076 handler::server::{router::tool::ToolRouter, tool::Parameters},
2077 model::*,
2078 schemars, tool, tool_handler, tool_router,
2079};
2080use serde::Deserialize;
2081use serde::de::DeserializeOwned;
2082 
2083const NWS_API_BASE: &str = "https://api.weather.gov";
2084const USER_AGENT: &str = "weather-app/1.0";
2085```
2086 
2087The `rmcp` crate provides the Model Context Protocol SDK for Rust, with features for server implementation, procedural macros, and stdio transport.
2088 
2089### Data structures
2090 
2091Next, let's define the data structures for deserializing responses from the National Weather Service API:
2092 
2093```rust theme={null}
2094#[derive(Debug, Deserialize)]
2095struct AlertsResponse {
2096 features: Vec<AlertFeature>,
2097}
2098 
2099#[derive(Debug, Deserialize)]
2100struct AlertFeature {
2101 properties: AlertProperties,
2102}
2103 
2104#[derive(Debug, Deserialize)]
2105struct AlertProperties {
2106 event: Option<String>,
2107 #[serde(rename = "areaDesc")]
2108 area_desc: Option<String>,
2109 severity: Option<String>,
2110 description: Option<String>,
2111 instruction: Option<String>,
2112}
2113 
2114#[derive(Debug, Deserialize)]
2115struct PointsResponse {
2116 properties: PointsProperties,
2117}
2118 
2119#[derive(Debug, Deserialize)]
2120struct PointsProperties {
2121 forecast: String,
2122}
2123 
2124#[derive(Debug, Deserialize)]
2125struct ForecastResponse {
2126 properties: ForecastProperties,
2127}
2128 
2129#[derive(Debug, Deserialize)]
2130struct ForecastProperties {
2131 periods: Vec<ForecastPeriod>,
2132}
2133 
2134#[derive(Debug, Deserialize)]
2135struct ForecastPeriod {
2136 name: String,
2137 temperature: i32,
2138 #[serde(rename = "temperatureUnit")]
2139 temperature_unit: String,
2140 #[serde(rename = "windSpeed")]
2141 wind_speed: String,
2142 #[serde(rename = "windDirection")]
2143 wind_direction: String,
2144 #[serde(rename = "detailedForecast")]
2145 detailed_forecast: String,
2146}
2147```
2148 
2149Now define the request types that MCP clients will send:
2150 
2151```rust theme={null}
2152#[derive(serde::Deserialize, schemars::JsonSchema)]
2153pub struct MCPForecastRequest {
2154 latitude: f32,
2155 longitude: f32,
2156}
2157 
2158#[derive(serde::Deserialize, schemars::JsonSchema)]
2159pub struct MCPAlertRequest {
2160 state: String,
2161}
2162```
2163 
2164### Helper functions
2165 
2166Add helper functions for making API requests and formatting responses:
2167 
2168```rust theme={null}
2169async fn make_nws_request<T: DeserializeOwned>(url: &str) -> Result<T> {
2170 let client = reqwest::Client::new();
2171 let rsp = client
2172 .get(url)
2173 .header(reqwest::header::USER_AGENT, USER_AGENT)
2174 .header(reqwest::header::ACCEPT, "application/geo+json")
2175 .send()
2176 .await?
2177 .error_for_status()?;
2178 Ok(rsp.json::<T>().await?)
2179}
2180 
2181fn format_alert(feature: &AlertFeature) -> String {
2182 let props = &feature.properties;
2183 format!(
2184 "Event: {}\nArea: {}\nSeverity: {}\nDescription: {}\nInstructions: {}",
2185 props.event.as_deref().unwrap_or("Unknown"),
2186 props.area_desc.as_deref().unwrap_or("Unknown"),
2187 props.severity.as_deref().unwrap_or("Unknown"),
2188 props
2189 .description
2190 .as_deref()
2191 .unwrap_or("No description available"),
2192 props
2193 .instruction
2194 .as_deref()
2195 .unwrap_or("No specific instructions provided")
2196 )
2197}
2198 
2199fn format_period(period: &ForecastPeriod) -> String {
2200 format!(
2201 "{}:\nTemperature: {}°{}\nWind: {} {}\nForecast: {}",
2202 period.name,
2203 period.temperature,
2204 period.temperature_unit,
2205 period.wind_speed,
2206 period.wind_direction,
2207 period.detailed_forecast
2208 )
2209}
2210```
2211 
2212### Implementing the Weather server and tools
2213 
2214Now let's implement the main Weather server struct with the tool handlers:
2215 
2216```rust theme={null}
2217pub struct Weather {
2218 tool_router: ToolRouter<Weather>,
2219}
2220 
2221#[tool_router]
2222impl Weather {
2223 fn new() -> Self {
2224 Self {
2225 tool_router: Self::tool_router(),
12162226 }
12172227 }
1218 ```
1219 
1220 ### Weather API helper functions
1221 
1222 Next, let's add functions and data classes for querying and converting responses from the National Weather Service API:
1223 
1224 ```kotlin theme={null}
1225 val httpClient = HttpClient(CIO) {
1226 defaultRequest {
1227 url("https://api.weather.gov")
1228 headers {
1229 append("Accept", "application/geo+json")
1230 append("User-Agent", "WeatherApiClient/1.0")
2228 
2229 #[tool(description = "Get weather alerts for a US state.")]
2230 async fn get_alerts(
2231 &self,
2232 Parameters(MCPAlertRequest { state }): Parameters<MCPAlertRequest>,
2233 ) -> String {
2234 let url = format!(
2235 "{}/alerts/active/area/{}",
2236 NWS_API_BASE,
2237 state.to_uppercase()
2238 );
2239 
2240 match make_nws_request::<AlertsResponse>(&url).await {
2241 Ok(data) => {
2242 if data.features.is_empty() {
2243 "No active alerts for this state.".to_string()
2244 } else {
2245 data.features
2246 .iter()
2247 .map(format_alert)
2248 .collect::<Vec<_>>()
2249 .join("\n---\n")
2250 }
12312251 }
1232 contentType(ContentType.Application.Json)
1233 }
1234 install(ContentNegotiation) {
1235 json(Json { ignoreUnknownKeys = true })
2252 Err(_) => "Unable to fetch alerts or no alerts found.".to_string(),
12362253 }
12372254 }
12382255 
1239 // Extension function to fetch weather alerts for a given state
1240 suspend fun HttpClient.getAlerts(state: String): List<String> {
1241 val alerts = this.get("/alerts/active/area/$state").body<AlertsResponse>()
1242 return alerts.features.map { feature ->
1243 """
1244 Event: ${feature.properties.event}
1245 Area: ${feature.properties.areaDesc}
1246 Severity: ${feature.properties.severity}
1247 Status: ${feature.properties.status}
1248 Headline: ${feature.properties.headline}
1249 """.trimIndent()
2256 #[tool(description = "Get weather forecast for a location.")]
2257 async fn get_forecast(
2258 &self,
2259 Parameters(MCPForecastRequest {
2260 latitude,
2261 longitude,
2262 }): Parameters<MCPForecastRequest>,
2263 ) -> String {
2264 let points_url = format!("{NWS_API_BASE}/points/{latitude},{longitude}");
2265 let Ok(points_data) = make_nws_request::<PointsResponse>(&points_url).await else {
2266 return "Unable to fetch forecast data for this location.".to_string();
2267 };
2268 
2269 let forecast_url = points_data.properties.forecast;
2270 
2271 let Ok(forecast_data) = make_nws_request::<ForecastResponse>(&forecast_url).await else {
2272 return "Unable to fetch forecast data for this location.".to_string();
2273 };
2274 
2275 let periods = &forecast_data.properties.periods;
2276 let forecast_summary: String = periods
2277 .iter()
2278 .take(5) // Next 5 periods only
2279 .map(format_period)
2280 .collect::<Vec<String>>()
2281 .join("\n---\n");
2282 forecast_summary
2283 }
2284}
2285```
2286 
2287The `#[tool_router]` macro automatically generates the routing logic, and the `#[tool]` attribute marks methods as MCP tools.
2288 
2289### Implementing the ServerHandler
2290 
2291Implement the `ServerHandler` trait to define server capabilities:
2292 
2293```rust theme={null}
2294#[tool_handler]
2295impl ServerHandler for Weather {
2296 fn get_info(&self) -> ServerInfo {
2297 ServerInfo {
2298 capabilities: ServerCapabilities::builder().enable_tools().build(),
2299 ..Default::default()
12502300 }
12512301 }
1252 
1253 // Extension function to fetch forecast information for given latitude and longitude
1254 suspend fun HttpClient.getForecast(latitude: Double, longitude: Double): List<String> {
1255 val points = this.get("/points/$latitude,$longitude").body<PointsResponse>()
1256 val forecastUrl = points.properties.forecast ?: error("No forecast URL available")
1257 val forecast = this.get(forecastUrl).body<ForecastResponse>()
1258 return forecast.properties.periods.map { period ->
1259 """
1260 ${period.name}:
1261 Temperature: ${period.temperature}°${period.temperatureUnit}
1262 Wind: ${period.windSpeed} ${period.windDirection}
1263 ${period.shortForecast}
1264 """.trimIndent()
1265 }
2302}
2303```
2304 
2305### Running the server
2306 
2307Finally, implement the main function to run the server with stdio transport:
2308 
2309```rust theme={null}
2310#[tokio::main]
2311async fn main() -> Result<()> {
2312 let transport = (tokio::io::stdin(), tokio::io::stdout());
2313 let service = Weather::new().serve(transport).await?;
2314 service.waiting().await?;
2315 Ok(())
2316}
2317```
2318 
2319Build your server with:
2320 
2321```bash theme={null}
2322cargo build --release
2323```
2324 
2325The compiled binary will be in `target/release/weather`.
2326 
2327Let's now test your server from an existing MCP host, Claude for Desktop.
2328 
2329## Testing your server with Claude for Desktop
2330 
2331First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
2332 
2333We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
2334 
2335For example, if you have [VS Code](https://code.visualstudio.com/) installed:
2336 
2337```bash Linux theme={null}
2338code ~/.config/Claude/claude_desktop_config.json
2339```
2340 
2341```bash macOS theme={null}
2342code ~/Library/Application\ Support/Claude/claude_desktop_config.json
2343```
2344 
2345```powershell Windows theme={null}
2346code $env:AppData\Claude\claude_desktop_config.json
2347```
2348 
2349You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
2350 
2351In this case, we'll add our single weather server like so:
2352 
2353```json macOS/Linux theme={null}
2354{
2355 "mcpServers": {
2356 "weather": {
2357 "command": "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/target/release/weather"
12662358 }
1267 
1268 @Serializable
1269 data class PointsResponse(val properties: PointsProperties)
1270 
1271 @Serializable
1272 data class PointsProperties(val forecast: String? = null)
1273 
1274 @Serializable
1275 data class ForecastResponse(val properties: ForecastProperties)
1276 
1277 @Serializable
1278 data class ForecastProperties(val periods: List<ForecastPeriod> = emptyList())
1279 
1280 @Serializable
1281 data class ForecastPeriod(
1282 val name: String? = null,
1283 val temperature: Int? = null,
1284 val temperatureUnit: String? = null,
1285 val windSpeed: String? = null,
1286 val windDirection: String? = null,
1287 val shortForecast: String? = null,
1288 )
1289 
1290 @Serializable
1291 data class AlertsResponse(val features: List<AlertFeature> = emptyList())
1292 
1293 @Serializable
1294 data class AlertFeature(val properties: AlertProperties)
1295 
1296 @Serializable
1297 data class AlertProperties(
1298 val event: String? = null,
1299 val areaDesc: String? = null,
1300 val severity: String? = null,
1301 val status: String? = null,
1302 val headline: String? = null,
1303 )
1304 ```
1305 
1306 ### Implementing tool execution
1307 
1308 The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
1309 
1310 ```kotlin theme={null}
1311 // Register weather tools
1312 
1313 server.addTool(
1314 name = "get_alerts",
1315 description = "Get weather alerts for a US state. Input is a two-letter US state code (e.g. CA, NY)",
1316 inputSchema = ToolSchema(
1317 properties = buildJsonObject {
1318 putJsonObject("state") {
1319 put("type", "string")
1320 put("description", "Two-letter US state code (e.g. CA, NY)")
1321 }
1322 },
1323 required = listOf("state"),
1324 ),
1325 ) { request ->
1326 val state = request.arguments?.get("state")?.jsonPrimitive?.content
1327 ?: return@addTool CallToolResult(
1328 content = listOf(TextContent("The 'state' parameter is required.")),
1329 )
1330 
1331 val alerts = httpClient.getAlerts(state)
1332 CallToolResult(content = alerts.map { TextContent(it) })
2359 }
2360}
2361```
2362 
2363```json Windows theme={null}
2364{
2365 "mcpServers": {
2366 "weather": {
2367 "command": "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\target\\release\\weather.exe"
13332368 }
1334 
1335 server.addTool(
1336 name = "get_forecast",
1337 description = "Get weather forecast for a location. Note: only US locations are supported by the NWS API.",
1338 inputSchema = ToolSchema(
1339 properties = buildJsonObject {
1340 putJsonObject("latitude") {
1341 put("type", "number")
1342 put("description", "Latitude of the location")
1343 }
1344 putJsonObject("longitude") {
1345 put("type", "number")
1346 put("description", "Longitude of the location")
1347 }
1348 },
1349 required = listOf("latitude", "longitude"),
1350 ),
1351 ) { request ->
1352 val latitude = request.arguments?.get("latitude")?.jsonPrimitive?.doubleOrNull
1353 val longitude = request.arguments?.get("longitude")?.jsonPrimitive?.doubleOrNull
1354 if (latitude == null || longitude == null) {
1355 return@addTool CallToolResult(
1356 content = listOf(TextContent("The 'latitude' and 'longitude' parameters are required.")),
1357 )
1358 }
1359 
1360 val forecast = httpClient.getForecast(latitude, longitude)
1361 CallToolResult(content = forecast.map { TextContent(it) })
2369 }
2370}
2371```
2372 
2373> [!NOTE]
2374>
2375> Make sure you pass in the absolute path to your compiled binary. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt from your project directory. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path, and add the `.exe` extension.
2376 
2377This tells Claude for Desktop:
2378 
23791. There's an MCP server named "weather"
23802. Launch it by running the compiled binary at the specified path
2381 
2382Save the file, and restart **Claude for Desktop**.
2383 
2384**Go**
2385 
2386Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-go)
2387 
2388### Prerequisite knowledge
2389 
2390This quickstart assumes you have familiarity with:
2391 
2392* Go
2393* LLMs like Claude
2394 
2395### Logging in MCP Servers
2396 
2397When implementing MCP servers, be careful about how you handle logging:
2398 
2399**For STDIO-based servers:** Never use `fmt.Println()` or `fmt.Printf()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
2400 
2401**For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
2402 
2403### Best Practices
2404 
2405* Use `log.Println()` (which defaults to stderr) or a logging library that writes to stderr or files.
2406* Use `fmt.Fprintf(os.Stderr, ...)` to write to stderr explicitly.
2407 
2408### Quick Examples
2409 
2410```go theme={null}
2411// ❌ Bad (STDIO)
2412fmt.Println("Processing request")
2413 
2414// ✅ Good (STDIO)
2415log.Println("Processing request") // defaults to stderr
2416 
2417// ✅ Good (STDIO)
2418fmt.Fprintln(os.Stderr, "Processing request")
2419```
2420 
2421### System requirements
2422 
2423* Go 1.24 or higher installed.
2424 
2425### Set up your environment
2426 
2427First, let's install Go if you haven't already. You can download and install Go from [go.dev](https://go.dev/dl/).
2428 
2429Verify your Go installation:
2430 
2431```bash theme={null}
2432go version
2433```
2434 
2435Now, let's create and set up our project:
2436 
2437```bash macOS/Linux theme={null}
2438# Create a new directory for our project
2439mkdir weather
2440cd weather
2441 
2442# Initialize Go module
2443go mod init weather
2444 
2445# Install dependencies
2446go get github.com/modelcontextprotocol/go-sdk/mcp
2447 
2448# Create our server file
2449touch main.go
2450```
2451 
2452```powershell Windows theme={null}
2453# Create a new directory for our project
2454md weather
2455cd weather
2456 
2457# Initialize Go module
2458go mod init weather
2459 
2460# Install dependencies
2461go get github.com/modelcontextprotocol/go-sdk/mcp
2462 
2463# Create our server file
2464new-item main.go
2465```
2466 
2467Now let's dive into building your server.
2468 
2469## Building your server
2470 
2471### Importing packages and constants
2472 
2473Add these to the top of your `main.go`:
2474 
2475```go theme={null}
2476package main
2477 
2478import (
2479 "cmp"
2480 "context"
2481 "encoding/json"
2482 "fmt"
2483 "io"
2484 "log"
2485 "net/http"
2486 "strings"
2487 
2488 "github.com/modelcontextprotocol/go-sdk/mcp"
2489)
2490 
2491const (
2492 NWSAPIBase = "https://api.weather.gov"
2493 UserAgent = "weather-app/1.0"
2494)
2495```
2496 
2497### Data structures
2498 
2499Next, let's define the data structures used by our tools:
2500 
2501```go theme={null}
2502type PointsResponse struct {
2503 Properties struct {
2504 Forecast string `json:"forecast"`
2505 } `json:"properties"`
2506}
2507 
2508type ForecastResponse struct {
2509 Properties struct {
2510 Periods []ForecastPeriod `json:"periods"`
2511 } `json:"properties"`
2512}
2513 
2514type ForecastPeriod struct {
2515 Name string `json:"name"`
2516 Temperature int `json:"temperature"`
2517 TemperatureUnit string `json:"temperatureUnit"`
2518 WindSpeed string `json:"windSpeed"`
2519 WindDirection string `json:"windDirection"`
2520 DetailedForecast string `json:"detailedForecast"`
2521}
2522 
2523type AlertsResponse struct {
2524 Features []AlertFeature `json:"features"`
2525}
2526 
2527type AlertFeature struct {
2528 Properties AlertProperties `json:"properties"`
2529}
2530 
2531type AlertProperties struct {
2532 Event string `json:"event"`
2533 AreaDesc string `json:"areaDesc"`
2534 Severity string `json:"severity"`
2535 Description string `json:"description"`
2536 Instruction string `json:"instruction"`
2537}
2538 
2539type ForecastInput struct {
2540 Latitude float64 `json:"latitude" jsonschema:"Latitude of the location"`
2541 Longitude float64 `json:"longitude" jsonschema:"Longitude of the location"`
2542}
2543 
2544type AlertsInput struct {
2545 State string `json:"state" jsonschema:"Two-letter US state code (e.g. CA, NY)"`
2546}
2547```
2548 
2549### Helper functions
2550 
2551Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
2552 
2553```go theme={null}
2554func makeNWSRequest[T any](ctx context.Context, url string) (*T, error) {
2555 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
2556 if err != nil {
2557 return nil, fmt.Errorf("failed to create request: %w", err)
2558 }
2559 
2560 req.Header.Set("User-Agent", UserAgent)
2561 req.Header.Set("Accept", "application/geo+json")
2562 
2563 client := http.DefaultClient
2564 resp, err := client.Do(req)
2565 if err != nil {
2566 return nil, fmt.Errorf("failed to make request to %s: %w", url, err)
2567 }
2568 defer resp.Body.Close()
2569 
2570 if resp.StatusCode != http.StatusOK {
2571 body, _ := io.ReadAll(resp.Body)
2572 return nil, fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body))
2573 }
2574 
2575 var result T
2576 if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
2577 return nil, fmt.Errorf("failed to decode response: %w", err)
2578 }
2579 
2580 return &result, nil
2581}
2582 
2583func formatAlert(alert AlertFeature) string {
2584 props := alert.Properties
2585 event := cmp.Or(props.Event, "Unknown")
2586 areaDesc := cmp.Or(props.AreaDesc, "Unknown")
2587 severity := cmp.Or(props.Severity, "Unknown")
2588 description := cmp.Or(props.Description, "No description available")
2589 instruction := cmp.Or(props.Instruction, "No specific instructions provided")
2590 
2591 return fmt.Sprintf(`
2592Event: %s
2593Area: %s
2594Severity: %s
2595Description: %s
2596Instructions: %s
2597`, event, areaDesc, severity, description, instruction)
2598}
2599 
2600func formatPeriod(period ForecastPeriod) string {
2601 return fmt.Sprintf(`
2602%s:
2603Temperature: %d°%s
2604Wind: %s %s
2605Forecast: %s
2606`, period.Name, period.Temperature, period.TemperatureUnit,
2607 period.WindSpeed, period.WindDirection, period.DetailedForecast)
2608}
2609```
2610 
2611### Implementing tool execution
2612 
2613The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
2614 
2615```go theme={null}
2616func getForecast(ctx context.Context, req *mcp.CallToolRequest, input ForecastInput) (
2617 *mcp.CallToolResult, any, error,
2618) {
2619 // Get points data
2620 pointsURL := fmt.Sprintf("%s/points/%f,%f", NWSAPIBase, input.Latitude, input.Longitude)
2621 pointsData, err := makeNWSRequest[PointsResponse](ctx, pointsURL)
2622 if err != nil {
2623 return &mcp.CallToolResult{
2624 Content: []mcp.Content{
2625 &mcp.TextContent{Text: "Unable to fetch forecast data for this location."},
2626 },
2627 }, nil, nil
2628 }
2629 
2630 // Get forecast data
2631 forecastURL := pointsData.Properties.Forecast
2632 if forecastURL == "" {
2633 return &mcp.CallToolResult{
2634 Content: []mcp.Content{
2635 &mcp.TextContent{Text: "Unable to fetch forecast URL."},
2636 },
2637 }, nil, nil
2638 }
2639 
2640 forecastData, err := makeNWSRequest[ForecastResponse](ctx, forecastURL)
2641 if err != nil {
2642 return &mcp.CallToolResult{
2643 Content: []mcp.Content{
2644 &mcp.TextContent{Text: "Unable to fetch detailed forecast."},
2645 },
2646 }, nil, nil
2647 }
2648 
2649 // Format the periods
2650 periods := forecastData.Properties.Periods
2651 if len(periods) == 0 {
2652 return &mcp.CallToolResult{
2653 Content: []mcp.Content{
2654 &mcp.TextContent{Text: "No forecast periods available."},
2655 },
2656 }, nil, nil
2657 }
2658 
2659 // Show next 5 periods
2660 var forecasts []string
2661 for i := range min(5, len(periods)) {
2662 forecasts = append(forecasts, formatPeriod(periods[i]))
2663 }
2664 
2665 result := strings.Join(forecasts, "\n---\n")
2666 
2667 return &mcp.CallToolResult{
2668 Content: []mcp.Content{
2669 &mcp.TextContent{Text: result},
2670 },
2671 }, nil, nil
2672}
2673 
2674func getAlerts(ctx context.Context, req *mcp.CallToolRequest, input AlertsInput) (
2675 *mcp.CallToolResult, any, error,
2676) {
2677 // Build alerts URL
2678 stateCode := strings.ToUpper(input.State)
2679 alertsURL := fmt.Sprintf("%s/alerts/active/area/%s", NWSAPIBase, stateCode)
2680 
2681 alertsData, err := makeNWSRequest[AlertsResponse](ctx, alertsURL)
2682 if err != nil {
2683 return &mcp.CallToolResult{
2684 Content: []mcp.Content{
2685 &mcp.TextContent{Text: "Unable to fetch alerts or no alerts found."},
2686 },
2687 }, nil, nil
2688 }
2689 
2690 // Check if there are any alerts
2691 if len(alertsData.Features) == 0 {
2692 return &mcp.CallToolResult{
2693 Content: []mcp.Content{
2694 &mcp.TextContent{Text: "No active alerts for this state."},
2695 },
2696 }, nil, nil
2697 }
2698 
2699 // Format alerts
2700 var alerts []string
2701 for _, feature := range alertsData.Features {
2702 alerts = append(alerts, formatAlert(feature))
2703 }
2704 
2705 result := strings.Join(alerts, "\n---\n")
2706 
2707 return &mcp.CallToolResult{
2708 Content: []mcp.Content{
2709 &mcp.TextContent{Text: result},
2710 },
2711 }, nil, nil
2712}
2713```
2714 
2715### Running the server
2716 
2717Finally, implement the main function to run the server:
2718 
2719```go theme={null}
2720func main() {
2721 // Create MCP server
2722 server := mcp.NewServer(&mcp.Implementation{
2723 Name: "weather",
2724 Version: "1.0.0",
2725 }, nil)
2726 
2727 // Add get_forecast tool
2728 mcp.AddTool(server, &mcp.Tool{
2729 Name: "get_forecast",
2730 Description: "Get weather forecast for a location",
2731 }, getForecast)
2732 
2733 // Add get_alerts tool
2734 mcp.AddTool(server, &mcp.Tool{
2735 Name: "get_alerts",
2736 Description: "Get weather alerts for a US state",
2737 }, getAlerts)
2738 
2739 // Run server on stdio transport
2740 if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil {
2741 log.Fatal(err)
2742 }
2743}
2744```
2745 
2746Build your server with:
2747 
2748```bash theme={null}
2749go build -o weather .
2750```
2751 
2752The compiled binary will be in `./weather`.
2753 
2754Let's now test your server from an existing MCP host, Claude for Desktop.
2755 
2756## Testing your server with Claude for Desktop
2757 
2758First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
2759 
2760We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
2761 
2762For example, if you have [VS Code](https://code.visualstudio.com/) installed:
2763 
2764```bash Linux theme={null}
2765code ~/.config/Claude/claude_desktop_config.json
2766```
2767 
2768```bash macOS theme={null}
2769code ~/Library/Application\ Support/Claude/claude_desktop_config.json
2770```
2771 
2772```powershell Windows theme={null}
2773code $env:AppData\Claude\claude_desktop_config.json
2774```
2775 
2776You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
2777 
2778In this case, we'll add our single weather server like so:
2779 
2780```json macOS/Linux theme={null}
2781{
2782 "mcpServers": {
2783 "weather": {
2784 "command": "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/weather"
13622785 }
1363 ```
1364 
1365 ### Running the server
1366 
1367 Finally, implement the main function to run the server:
1368 
1369 ```kotlin theme={null}
1370 fun main() = runMcpServer()
1371 ```
1372 
1373 You can run the server directly during development:
1374 
1375 ```bash theme={null}
1376 ./gradlew run
1377 ```
1378 
1379 For production use, build the shadow JAR:
1380 
1381 ```bash theme={null}
1382 ./gradlew build
1383 java -jar build/libs/weather-0.1.0-all.jar
1384 ```
1385 
1386 Let's now test your server from an existing MCP host, Claude for Desktop.
1387 
1388 ## Testing your server with Claude for Desktop
1389 
1390 First, make sure you have Claude for Desktop installed. [You can install the latest version
1391 here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
1392 
1393 We'll need to configure Claude for Desktop for whichever MCP servers you want to use.
1394 To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor.
1395 Make sure to create the file if it doesn't exist.
1396 
1397 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
1398 
1399 <CodeGroup>
1400 ```bash Linux theme={null}
1401 code ~/.config/Claude/claude_desktop_config.json
1402 ```
1403 
1404 ```bash macOS theme={null}
1405 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
1406 ```
1407 
1408 ```powershell Windows theme={null}
1409 code $env:AppData\Claude\claude_desktop_config.json
1410 ```
1411 </CodeGroup>
1412 
1413 You'll then add your servers in the `mcpServers` key.
1414 The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
1415 
1416 In this case, we'll add our single weather server like so:
1417 
1418 <CodeGroup>
1419 ```json macOS/Linux theme={null}
1420 {
1421 "mcpServers": {
1422 "weather": {
1423 "command": "java",
1424 "args": [
1425 "-jar",
1426 "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/libs/weather-0.1.0-all.jar"
1427 ]
1428 }
1429 }
1430 }
1431 ```
1432 
1433 ```json Windows theme={null}
1434 {
1435 "mcpServers": {
1436 "weather": {
1437 "command": "java",
1438 "args": [
1439 "-jar",
1440 "C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\libs\\weather-0.1.0-all.jar"
1441 ]
1442 }
1443 }
1444 }
1445 ```
1446 </CodeGroup>
1447 
1448 This tells Claude for Desktop:
1449 
1450 1. There's an MCP server named "weather"
1451 2. Launch it by running `java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/libs/weather-0.1.0-all.jar`
1452 
1453 Save the file, and restart **Claude for Desktop**.
1454 </Tab>
1455 
1456 <Tab title="C#">
1457 Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/csharp-sdk/tree/main/samples/QuickstartWeatherServer)
1458 
1459 ### Prerequisite knowledge
1460 
1461 This quickstart assumes you have familiarity with:
1462 
1463 * C#
1464 * LLMs like Claude
1465 * .NET 8 or higher
1466 
1467 ### Logging in MCP Servers
1468 
1469 When implementing MCP servers, be careful about how you handle logging:
1470 
1471 **For STDIO-based servers:** Never use `Console.WriteLine()` or `Console.Write()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
1472 
1473 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
1474 
1475 ### Best Practices
1476 
1477 * Use a logging library that writes to stderr or files.
1478 
1479 ### System requirements
1480 
1481 * [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) or higher installed.
1482 
1483 ### Set up your environment
1484 
1485 First, let's install `dotnet` if you haven't already. You can download `dotnet` from [official Microsoft .NET website](https://dotnet.microsoft.com/download/). Verify your `dotnet` installation:
1486 
1487 ```bash theme={null}
1488 dotnet --version
1489 ```
1490 
1491 Now, let's create and set up your project:
1492 
1493 <CodeGroup>
1494 ```bash macOS/Linux theme={null}
1495 # Create a new directory for our project
1496 mkdir weather
1497 cd weather
1498 # Initialize a new C# project
1499 dotnet new console
1500 ```
1501 
1502 ```powershell Windows theme={null}
1503 # Create a new directory for our project
1504 mkdir weather
1505 cd weather
1506 # Initialize a new C# project
1507 dotnet new console
1508 ```
1509 </CodeGroup>
1510 
1511 After running `dotnet new console`, you will be presented with a new C# project.
1512 You can open the project in your favorite IDE, such as [Visual Studio](https://visualstudio.microsoft.com/) or [Rider](https://www.jetbrains.com/rider/).
1513 Alternatively, you can create a C# application using the [Visual Studio project wizard](https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-console?view=vs-2022).
1514 After creating the project, add NuGet package for the Model Context Protocol SDK and hosting:
1515 
1516 ```bash theme={null}
1517 # Add the Model Context Protocol SDK NuGet package
1518 dotnet add package ModelContextProtocol --prerelease
1519 # Add the .NET Hosting NuGet package
1520 dotnet add package Microsoft.Extensions.Hosting
1521 ```
1522 
1523 Now let’s dive into building your server.
1524 
1525 ## Building your server
1526 
1527 Open the `Program.cs` file in your project and replace its contents with the following code:
1528 
1529 ```csharp theme={null}
1530 using Microsoft.Extensions.DependencyInjection;
1531 using Microsoft.Extensions.Hosting;
1532 using ModelContextProtocol;
1533 using System.Net.Http.Headers;
1534 
1535 var builder = Host.CreateEmptyApplicationBuilder(settings: null);
1536 
1537 builder.Services.AddMcpServer()
1538 .WithStdioServerTransport()
1539 .WithToolsFromAssembly();
1540 
1541 builder.Services.AddSingleton(_ =>
1542 {
1543 var client = new HttpClient() { BaseAddress = new Uri("https://api.weather.gov") };
1544 client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("weather-tool", "1.0"));
1545 return client;
1546 });
1547 
1548 var app = builder.Build();
1549 
1550 await app.RunAsync();
1551 ```
1552 
1553 <Note>
1554 When creating the `ApplicationHostBuilder`, ensure you use `CreateEmptyApplicationBuilder` instead of `CreateDefaultBuilder`. This ensures that the server does not write any additional messages to the console. This is only necessary for servers using STDIO transport.
1555 </Note>
1556 
1557 This code sets up a basic console application that uses the Model Context Protocol SDK to create an MCP server with standard I/O transport.
1558 
1559 ### Weather API helper functions
1560 
1561 Create an extension class for `HttpClient` which helps simplify JSON request handling:
1562 
1563 ```csharp theme={null}
1564 using System.Text.Json;
1565 
1566 internal static class HttpClientExt
1567 {
1568 public static async Task<JsonDocument> ReadJsonDocumentAsync(this HttpClient client, string requestUri)
1569 {
1570 using var response = await client.GetAsync(requestUri);
1571 response.EnsureSuccessStatusCode();
1572 return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
1573 }
2786 }
2787}
2788```
2789 
2790```json Windows theme={null}
2791{
2792 "mcpServers": {
2793 "weather": {
2794 "command": "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\weather.exe"
15742795 }
1575 ```
1576 
1577 Next, define a class with the tool execution handlers for querying and converting responses from the National Weather Service API:
1578 
1579 ```csharp theme={null}
1580 using ModelContextProtocol.Server;
1581 using System.ComponentModel;
1582 using System.Globalization;
1583 using System.Text.Json;
1584 
1585 namespace QuickstartWeatherServer.Tools;
1586 
1587 [McpServerToolType]
1588 public static class WeatherTools
1589 {
1590 [McpServerTool, Description("Get weather alerts for a US state code.")]
1591 public static async Task<string> GetAlerts(
1592 HttpClient client,
1593 [Description("The US state code to get alerts for.")] string state)
1594 {
1595 using var jsonDocument = await client.ReadJsonDocumentAsync($"/alerts/active/area/{state}");
1596 var jsonElement = jsonDocument.RootElement;
1597 var alerts = jsonElement.GetProperty("features").EnumerateArray();
1598 
1599 if (!alerts.Any())
1600 {
1601 return "No active alerts for this state.";
1602 }
1603 
1604 return string.Join("\n--\n", alerts.Select(alert =>
1605 {
1606 JsonElement properties = alert.GetProperty("properties");
1607 return $"""
1608 Event: {properties.GetProperty("event").GetString()}
1609 Area: {properties.GetProperty("areaDesc").GetString()}
1610 Severity: {properties.GetProperty("severity").GetString()}
1611 Description: {properties.GetProperty("description").GetString()}
1612 Instruction: {properties.GetProperty("instruction").GetString()}
1613 """;
1614 }));
1615 }
1616 
1617 [McpServerTool, Description("Get weather forecast for a location.")]
1618 public static async Task<string> GetForecast(
1619 HttpClient client,
1620 [Description("Latitude of the location.")] double latitude,
1621 [Description("Longitude of the location.")] double longitude)
1622 {
1623 var pointUrl = string.Create(CultureInfo.InvariantCulture, $"/points/{latitude},{longitude}");
1624 using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);
1625 var forecastUrl = jsonDocument.RootElement.GetProperty("properties").GetProperty("forecast").GetString()
1626 ?? throw new Exception($"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}");
1627 
1628 using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl);
1629 var periods = forecastDocument.RootElement.GetProperty("properties").GetProperty("periods").EnumerateArray();
1630 
1631 return string.Join("\n---\n", periods.Select(period => $"""
1632 {period.GetProperty("name").GetString()}
1633 Temperature: {period.GetProperty("temperature").GetInt32()}°F
1634 Wind: {period.GetProperty("windSpeed").GetString()} {period.GetProperty("windDirection").GetString()}
1635 Forecast: {period.GetProperty("detailedForecast").GetString()}
1636 """));
1637 }
1638 }
1639 ```
1640 
1641 ### Running the server
1642 
1643 Finally, run the server using the following command:
1644 
1645 ```bash theme={null}
1646 dotnet run
1647 ```
1648 
1649 This will start the server and listen for incoming requests on standard input/output.
1650 
1651 ## Testing your server with Claude for Desktop
1652 
1653 First, make sure you have Claude for Desktop installed. [You can install the latest version
1654 here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
1655 We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
1656 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
1657 
1658 <CodeGroup>
1659 ```bash Linux theme={null}
1660 code ~/.config/Claude/claude_desktop_config.json
1661 ```
1662 
1663 ```bash macOS theme={null}
1664 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
1665 ```
1666 
1667 ```powershell Windows theme={null}
1668 code $env:AppData\Claude\claude_desktop_config.json
1669 ```
1670 </CodeGroup>
1671 
1672 You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
1673 In this case, we'll add our single weather server like so:
1674 
1675 <CodeGroup>
1676 ```json macOS/Linux theme={null}
1677 {
1678 "mcpServers": {
1679 "weather": {
1680 "command": "dotnet",
1681 "args": ["run", "--project", "/ABSOLUTE/PATH/TO/PROJECT", "--no-build"]
1682 }
1683 }
1684 }
1685 ```
1686 
1687 ```json Windows theme={null}
1688 {
1689 "mcpServers": {
1690 "weather": {
1691 "command": "dotnet",
1692 "args": [
1693 "run",
1694 "--project",
1695 "C:\\ABSOLUTE\\PATH\\TO\\PROJECT",
1696 "--no-build"
1697 ]
1698 }
1699 }
1700 }
1701 ```
1702 </CodeGroup>
1703 
1704 This tells Claude for Desktop:
1705 
1706 1. There's an MCP server named "weather"
1707 2. Launch it by running `dotnet run /ABSOLUTE/PATH/TO/PROJECT`
1708 Save the file, and restart **Claude for Desktop**.
1709 </Tab>
1710 
1711 <Tab title="Ruby">
1712 Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-ruby)
1713 
1714 ### Prerequisite knowledge
1715 
1716 This quickstart assumes you have familiarity with:
1717 
1718 * Ruby
1719 * LLMs like Claude
1720 
1721 ### Logging in MCP Servers
1722 
1723 When implementing MCP servers, be careful about how you handle logging:
1724 
1725 **For STDIO-based servers:** Never use `puts` or `print`, as they write to standard output (stdout) by default. Writing to stdout will corrupt the JSON-RPC messages and break your server.
1726 
1727 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
1728 
1729 ### Best Practices
1730 
1731 * Use a logging library that writes to stderr or files.
1732 
1733 ### Quick Examples
1734 
1735 ```ruby theme={null}
1736 # ❌ Bad (STDIO)
1737 puts "Processing request"
1738 
1739 # ✅ Good (STDIO)
1740 require "logger"
1741 logger = Logger.new($stderr)
1742 logger.info("Processing request")
1743 ```
1744 
1745 ### System requirements
1746 
1747 * Ruby 2.7 or higher installed.
1748 
1749 ### Set up your environment
1750 
1751 First, let's make sure you have Ruby installed. You can check by running:
1752 
1753 ```bash theme={null}
1754 ruby --version
1755 ```
1756 
1757 Now, let's create and set up our project:
1758 
1759 <CodeGroup>
1760 ```bash macOS/Linux theme={null}
1761 # Create a new directory for our project
1762 mkdir weather
1763 cd weather
1764 
1765 # Create a Gemfile
1766 bundle init
1767 
1768 # Add the MCP SDK dependency
1769 bundle add mcp
1770 
1771 # Create our server file
1772 touch weather.rb
1773 ```
1774 
1775 ```powershell Windows theme={null}
1776 # Create a new directory for our project
1777 mkdir weather
1778 cd weather
1779 
1780 # Create a Gemfile
1781 bundle init
1782 
1783 # Add the MCP SDK dependency
1784 bundle add mcp
1785 
1786 # Create our server file
1787 new-item weather.rb
1788 ```
1789 </CodeGroup>
1790 
1791 Now let's dive into building your server.
1792 
1793 ## Building your server
1794 
1795 ### Importing packages and setting up constants
1796 
1797 Open `weather.rb` and add these requires and constants at the top:
1798 
1799 ```ruby theme={null}
1800 require "json"
1801 require "mcp"
1802 require "net/http"
1803 require "uri"
1804 
1805 NWS_API_BASE = "https://api.weather.gov"
1806 USER_AGENT = "weather-app/1.0"
1807 ```
1808 
1809 The `mcp` gem provides the Model Context Protocol SDK for Ruby, with classes for server implementation and stdio transport.
1810 
1811 ### Helper methods
1812 
1813 Next, let's add helper methods for querying and formatting data from the National Weather Service API:
1814 
1815 ```ruby theme={null}
1816 module HelperMethods
1817 def make_nws_request(url)
1818 uri = URI(url)
1819 request = Net::HTTP::Get.new(uri)
1820 request["User-Agent"] = USER_AGENT
1821 request["Accept"] = "application/geo+json"
1822 
1823 response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
1824 http.request(request)
1825 end
1826 
1827 raise "HTTP #{response.code}: #{response.message}" unless response.is_a?(Net::HTTPSuccess)
1828 
1829 JSON.parse(response.body)
1830 end
1831 
1832 def format_alert(feature)
1833 properties = feature["properties"]
1834 
1835 <<~ALERT
1836 Event: #{properties["event"] || "Unknown"}
1837 Area: #{properties["areaDesc"] || "Unknown"}
1838 Severity: #{properties["severity"] || "Unknown"}
1839 Description: #{properties["description"] || "No description available"}
1840 Instructions: #{properties["instruction"] || "No specific instructions provided"}
1841 ALERT
1842 end
1843 end
1844 ```
1845 
1846 ### Implementing tool execution
1847 
1848 Now let's define our tool classes. Each tool subclasses `MCP::Tool` and implements the tool logic:
1849 
1850 ```ruby theme={null}
1851 class GetAlerts < MCP::Tool
1852 extend HelperMethods
1853 
1854 tool_name "get_alerts"
1855 description "Get weather alerts for a US state"
1856 input_schema(
1857 properties: {
1858 state: {
1859 type: "string",
1860 description: "Two-letter US state code (e.g. CA, NY)"
1861 }
1862 },
1863 required: ["state"]
1864 )
1865 
1866 def self.call(state:)
1867 url = "#{NWS_API_BASE}/alerts/active/area/#{state.upcase}"
1868 data = make_nws_request(url)
1869 
1870 if data["features"].empty?
1871 return MCP::Tool::Response.new([{
1872 type: "text",
1873 text: "No active alerts for this state."
1874 }])
1875 end
1876 
1877 alerts = data["features"].map { |feature| format_alert(feature) }
1878 MCP::Tool::Response.new([{
1879 type: "text",
1880 text: alerts.join("\n---\n")
1881 }])
1882 end
1883 end
1884 
1885 class GetForecast < MCP::Tool
1886 extend HelperMethods
1887 
1888 tool_name "get_forecast"
1889 description "Get weather forecast for a location"
1890 input_schema(
1891 properties: {
1892 latitude: {
1893 type: "number",
1894 description: "Latitude of the location"
1895 },
1896 longitude: {
1897 type: "number",
1898 description: "Longitude of the location"
1899 }
1900 },
1901 required: ["latitude", "longitude"]
1902 )
1903 
1904 def self.call(latitude:, longitude:)
1905 # First get the forecast grid endpoint.
1906 points_url = "#{NWS_API_BASE}/points/#{latitude},#{longitude}"
1907 points_data = make_nws_request(points_url)
1908 
1909 # Get the forecast URL from the points response.
1910 forecast_url = points_data["properties"]["forecast"]
1911 forecast_data = make_nws_request(forecast_url)
1912 
1913 # Format the periods into a readable forecast.
1914 periods = forecast_data["properties"]["periods"]
1915 forecasts = periods.first(5).map do |period|
1916 <<~FORECAST
1917 #{period["name"]}:
1918 Temperature: #{period["temperature"]}°#{period["temperatureUnit"]}
1919 Wind: #{period["windSpeed"]} #{period["windDirection"]}
1920 Forecast: #{period["detailedForecast"]}
1921 FORECAST
1922 end
1923 
1924 MCP::Tool::Response.new([{
1925 type: "text",
1926 text: forecasts.join("\n---\n")
1927 }])
1928 end
1929 end
1930 ```
1931 
1932 ### Running the server
1933 
1934 Finally, initialize and run the server:
1935 
1936 ```ruby theme={null}
1937 server = MCP::Server.new(
1938 name: "weather",
1939 version: "1.0.0",
1940 tools: [GetAlerts, GetForecast]
1941 )
1942 
1943 transport = MCP::Server::Transports::StdioTransport.new(server)
1944 transport.open
1945 ```
1946 
1947 Your server is complete! Run `bundle exec ruby weather.rb` to start the MCP server, which will listen for messages from MCP hosts.
1948 
1949 Let's now test your server from an existing MCP host, Claude for Desktop.
1950 
1951 ## Testing your server with Claude for Desktop
1952 
1953 First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
1954 
1955 We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
1956 
1957 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
1958 
1959 <CodeGroup>
1960 ```bash Linux theme={null}
1961 code ~/.config/Claude/claude_desktop_config.json
1962 ```
1963 
1964 ```bash macOS theme={null}
1965 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
1966 ```
1967 
1968 ```powershell Windows theme={null}
1969 code $env:AppData\Claude\claude_desktop_config.json
1970 ```
1971 </CodeGroup>
1972 
1973 You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
1974 
1975 In this case, we'll add our single weather server like so:
1976 
1977 <CodeGroup>
1978 ```json macOS/Linux theme={null}
1979 {
1980 "mcpServers": {
1981 "weather": {
1982 "command": "bundle",
1983 "args": ["exec", "ruby", "weather.rb"],
1984 "cwd": "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather"
1985 }
1986 }
1987 }
1988 ```
1989 
1990 ```json Windows theme={null}
1991 {
1992 "mcpServers": {
1993 "weather": {
1994 "command": "bundle",
1995 "args": ["exec", "ruby", "weather.rb"],
1996 "cwd": "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather"
1997 }
1998 }
1999 }
2000 ```
2001 </CodeGroup>
2002 
2003 <Note>
2004 Make sure you pass in the absolute path to your project directory in the `cwd` field. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt from your project directory. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path.
2005 </Note>
2006 
2007 This tells Claude for Desktop:
2008 
2009 1. There's an MCP server named "weather"
2010 2. Launch it by running `bundle exec ruby weather.rb` in the specified directory
2011 
2012 Save the file, and restart **Claude for Desktop**.
2013 </Tab>
2014 
2015 <Tab title="Rust">
2016 Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-rust)
2017 
2018 ### Prerequisite knowledge
2019 
2020 This quickstart assumes you have familiarity with:
2021 
2022 * Rust programming language
2023 * Async/await in Rust
2024 * LLMs like Claude
2025 
2026 ### Logging in MCP Servers
2027 
2028 When implementing MCP servers, be careful about how you handle logging:
2029 
2030 **For STDIO-based servers:** Never use `println!()` or `print!()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
2031 
2032 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
2033 
2034 ### Best Practices
2035 
2036 * Use a logging library that writes to stderr or files, such as `tracing` or `log` in Rust.
2037 * Configure your logging framework to avoid stdout output.
2038 
2039 ### Quick Examples
2040 
2041 ```rust theme={null}
2042 // ❌ Bad (STDIO)
2043 println!("Processing request");
2044 
2045 // ✅ Good (STDIO)
2046 eprintln!("Processing request"); // writes to stderr
2047 ```
2048 
2049 ### System requirements
2050 
2051 * Rust 1.70 or higher installed.
2052 * Cargo (comes with Rust installation).
2053 
2054 ### Set up your environment
2055 
2056 First, let's install Rust if you haven't already. You can install Rust from [rust-lang.org](https://www.rust-lang.org/tools/install):
2057 
2058 <CodeGroup>
2059 ```bash macOS/Linux theme={null}
2060 curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
2061 ```
2062 
2063 ```powershell Windows theme={null}
2064 # Download and run rustup-init.exe from https://rustup.rs/
2065 ```
2066 </CodeGroup>
2067 
2068 Verify your Rust installation:
2069 
2070 ```bash theme={null}
2071 rustc --version
2072 cargo --version
2073 ```
2074 
2075 Now, let's create and set up our project:
2076 
2077 <CodeGroup>
2078 ```bash macOS/Linux theme={null}
2079 # Create a new Rust project
2080 cargo new weather
2081 cd weather
2082 ```
2083 
2084 ```powershell Windows theme={null}
2085 # Create a new Rust project
2086 cargo new weather
2087 cd weather
2088 ```
2089 </CodeGroup>
2090 
2091 Update your `Cargo.toml` to add the required dependencies:
2092 
2093 ```toml Cargo.toml theme={null}
2094 [package]
2095 name = "weather"
2096 version = "0.1.0"
2097 edition = "2024"
2098 
2099 [dependencies]
2100 rmcp = { version = "0.3", features = ["server", "macros", "transport-io"] }
2101 tokio = { version = "1.46", features = ["full"] }
2102 reqwest = { version = "0.12", features = ["json"] }
2103 serde = { version = "1.0", features = ["derive"] }
2104 serde_json = "1.0"
2105 anyhow = "1.0"
2106 tracing = "0.1"
2107 tracing-subscriber = { version = "0.3", features = ["env-filter", "std", "fmt"] }
2108 ```
2109 
2110 Now let's dive into building your server.
2111 
2112 ## Building your server
2113 
2114 ### Importing packages and constants
2115 
2116 Open `src/main.rs` and add these imports and constants at the top:
2117 
2118 ```rust theme={null}
2119 use anyhow::Result;
2120 use rmcp::{
2121 ServerHandler, ServiceExt,
2122 handler::server::{router::tool::ToolRouter, tool::Parameters},
2123 model::*,
2124 schemars, tool, tool_handler, tool_router,
2125 };
2126 use serde::Deserialize;
2127 use serde::de::DeserializeOwned;
2128 
2129 const NWS_API_BASE: &str = "https://api.weather.gov";
2130 const USER_AGENT: &str = "weather-app/1.0";
2131 ```
2132 
2133 The `rmcp` crate provides the Model Context Protocol SDK for Rust, with features for server implementation, procedural macros, and stdio transport.
2134 
2135 ### Data structures
2136 
2137 Next, let's define the data structures for deserializing responses from the National Weather Service API:
2138 
2139 ```rust theme={null}
2140 #[derive(Debug, Deserialize)]
2141 struct AlertsResponse {
2142 features: Vec<AlertFeature>,
2143 }
2144 
2145 #[derive(Debug, Deserialize)]
2146 struct AlertFeature {
2147 properties: AlertProperties,
2148 }
2149 
2150 #[derive(Debug, Deserialize)]
2151 struct AlertProperties {
2152 event: Option<String>,
2153 #[serde(rename = "areaDesc")]
2154 area_desc: Option<String>,
2155 severity: Option<String>,
2156 description: Option<String>,
2157 instruction: Option<String>,
2158 }
2159 
2160 #[derive(Debug, Deserialize)]
2161 struct PointsResponse {
2162 properties: PointsProperties,
2163 }
2164 
2165 #[derive(Debug, Deserialize)]
2166 struct PointsProperties {
2167 forecast: String,
2168 }
2169 
2170 #[derive(Debug, Deserialize)]
2171 struct ForecastResponse {
2172 properties: ForecastProperties,
2173 }
2174 
2175 #[derive(Debug, Deserialize)]
2176 struct ForecastProperties {
2177 periods: Vec<ForecastPeriod>,
2178 }
2179 
2180 #[derive(Debug, Deserialize)]
2181 struct ForecastPeriod {
2182 name: String,
2183 temperature: i32,
2184 #[serde(rename = "temperatureUnit")]
2185 temperature_unit: String,
2186 #[serde(rename = "windSpeed")]
2187 wind_speed: String,
2188 #[serde(rename = "windDirection")]
2189 wind_direction: String,
2190 #[serde(rename = "detailedForecast")]
2191 detailed_forecast: String,
2192 }
2193 ```
2194 
2195 Now define the request types that MCP clients will send:
2196 
2197 ```rust theme={null}
2198 #[derive(serde::Deserialize, schemars::JsonSchema)]
2199 pub struct MCPForecastRequest {
2200 latitude: f32,
2201 longitude: f32,
2202 }
2203 
2204 #[derive(serde::Deserialize, schemars::JsonSchema)]
2205 pub struct MCPAlertRequest {
2206 state: String,
2207 }
2208 ```
2209 
2210 ### Helper functions
2211 
2212 Add helper functions for making API requests and formatting responses:
2213 
2214 ```rust theme={null}
2215 async fn make_nws_request<T: DeserializeOwned>(url: &str) -> Result<T> {
2216 let client = reqwest::Client::new();
2217 let rsp = client
2218 .get(url)
2219 .header(reqwest::header::USER_AGENT, USER_AGENT)
2220 .header(reqwest::header::ACCEPT, "application/geo+json")
2221 .send()
2222 .await?
2223 .error_for_status()?;
2224 Ok(rsp.json::<T>().await?)
2225 }
2226 
2227 fn format_alert(feature: &AlertFeature) -> String {
2228 let props = &feature.properties;
2229 format!(
2230 "Event: {}\nArea: {}\nSeverity: {}\nDescription: {}\nInstructions: {}",
2231 props.event.as_deref().unwrap_or("Unknown"),
2232 props.area_desc.as_deref().unwrap_or("Unknown"),
2233 props.severity.as_deref().unwrap_or("Unknown"),
2234 props
2235 .description
2236 .as_deref()
2237 .unwrap_or("No description available"),
2238 props
2239 .instruction
2240 .as_deref()
2241 .unwrap_or("No specific instructions provided")
2242 )
2243 }
2244 
2245 fn format_period(period: &ForecastPeriod) -> String {
2246 format!(
2247 "{}:\nTemperature: {}°{}\nWind: {} {}\nForecast: {}",
2248 period.name,
2249 period.temperature,
2250 period.temperature_unit,
2251 period.wind_speed,
2252 period.wind_direction,
2253 period.detailed_forecast
2254 )
2255 }
2256 ```
2257 
2258 ### Implementing the Weather server and tools
2259 
2260 Now let's implement the main Weather server struct with the tool handlers:
2261 
2262 ```rust theme={null}
2263 pub struct Weather {
2264 tool_router: ToolRouter<Weather>,
2265 }
2266 
2267 #[tool_router]
2268 impl Weather {
2269 fn new() -> Self {
2270 Self {
2271 tool_router: Self::tool_router(),
2272 }
2273 }
2274 
2275 #[tool(description = "Get weather alerts for a US state.")]
2276 async fn get_alerts(
2277 &self,
2278 Parameters(MCPAlertRequest { state }): Parameters<MCPAlertRequest>,
2279 ) -> String {
2280 let url = format!(
2281 "{}/alerts/active/area/{}",
2282 NWS_API_BASE,
2283 state.to_uppercase()
2284 );
2285 
2286 match make_nws_request::<AlertsResponse>(&url).await {
2287 Ok(data) => {
2288 if data.features.is_empty() {
2289 "No active alerts for this state.".to_string()
2290 } else {
2291 data.features
2292 .iter()
2293 .map(format_alert)
2294 .collect::<Vec<_>>()
2295 .join("\n---\n")
2296 }
2297 }
2298 Err(_) => "Unable to fetch alerts or no alerts found.".to_string(),
2299 }
2300 }
2301 
2302 #[tool(description = "Get weather forecast for a location.")]
2303 async fn get_forecast(
2304 &self,
2305 Parameters(MCPForecastRequest {
2306 latitude,
2307 longitude,
2308 }): Parameters<MCPForecastRequest>,
2309 ) -> String {
2310 let points_url = format!("{NWS_API_BASE}/points/{latitude},{longitude}");
2311 let Ok(points_data) = make_nws_request::<PointsResponse>(&points_url).await else {
2312 return "Unable to fetch forecast data for this location.".to_string();
2313 };
2314 
2315 let forecast_url = points_data.properties.forecast;
2316 
2317 let Ok(forecast_data) = make_nws_request::<ForecastResponse>(&forecast_url).await else {
2318 return "Unable to fetch forecast data for this location.".to_string();
2319 };
2320 
2321 let periods = &forecast_data.properties.periods;
2322 let forecast_summary: String = periods
2323 .iter()
2324 .take(5) // Next 5 periods only
2325 .map(format_period)
2326 .collect::<Vec<String>>()
2327 .join("\n---\n");
2328 forecast_summary
2329 }
2330 }
2331 ```
2332 
2333 The `#[tool_router]` macro automatically generates the routing logic, and the `#[tool]` attribute marks methods as MCP tools.
2334 
2335 ### Implementing the ServerHandler
2336 
2337 Implement the `ServerHandler` trait to define server capabilities:
2338 
2339 ```rust theme={null}
2340 #[tool_handler]
2341 impl ServerHandler for Weather {
2342 fn get_info(&self) -> ServerInfo {
2343 ServerInfo {
2344 capabilities: ServerCapabilities::builder().enable_tools().build(),
2345 ..Default::default()
2346 }
2347 }
2348 }
2349 ```
2350 
2351 ### Running the server
2352 
2353 Finally, implement the main function to run the server with stdio transport:
2354 
2355 ```rust theme={null}
2356 #[tokio::main]
2357 async fn main() -> Result<()> {
2358 let transport = (tokio::io::stdin(), tokio::io::stdout());
2359 let service = Weather::new().serve(transport).await?;
2360 service.waiting().await?;
2361 Ok(())
2362 }
2363 ```
2364 
2365 Build your server with:
2366 
2367 ```bash theme={null}
2368 cargo build --release
2369 ```
2370 
2371 The compiled binary will be in `target/release/weather`.
2372 
2373 Let's now test your server from an existing MCP host, Claude for Desktop.
2374 
2375 ## Testing your server with Claude for Desktop
2376 
2377 First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
2378 
2379 We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
2380 
2381 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
2382 
2383 <CodeGroup>
2384 ```bash Linux theme={null}
2385 code ~/.config/Claude/claude_desktop_config.json
2386 ```
2387 
2388 ```bash macOS theme={null}
2389 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
2390 ```
2391 
2392 ```powershell Windows theme={null}
2393 code $env:AppData\Claude\claude_desktop_config.json
2394 ```
2395 </CodeGroup>
2396 
2397 You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
2398 
2399 In this case, we'll add our single weather server like so:
2400 
2401 <CodeGroup>
2402 ```json macOS/Linux theme={null}
2403 {
2404 "mcpServers": {
2405 "weather": {
2406 "command": "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/target/release/weather"
2407 }
2408 }
2409 }
2410 ```
2411 
2412 ```json Windows theme={null}
2413 {
2414 "mcpServers": {
2415 "weather": {
2416 "command": "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\target\\release\\weather.exe"
2417 }
2418 }
2419 }
2420 ```
2421 </CodeGroup>
2422 
2423 <Note>
2424 Make sure you pass in the absolute path to your compiled binary. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt from your project directory. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path, and add the `.exe` extension.
2425 </Note>
2426 
2427 This tells Claude for Desktop:
2428 
2429 1. There's an MCP server named "weather"
2430 2. Launch it by running the compiled binary at the specified path
2431 
2432 Save the file, and restart **Claude for Desktop**.
2433 </Tab>
2434 
2435 <Tab title="Go">
2436 Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-go)
2437 
2438 ### Prerequisite knowledge
2439 
2440 This quickstart assumes you have familiarity with:
2441 
2442 * Go
2443 * LLMs like Claude
2444 
2445 ### Logging in MCP Servers
2446 
2447 When implementing MCP servers, be careful about how you handle logging:
2448 
2449 **For STDIO-based servers:** Never use `fmt.Println()` or `fmt.Printf()`, as they write to standard output (stdout). Writing to stdout will corrupt the JSON-RPC messages and break your server.
2450 
2451 **For HTTP-based servers:** Standard output logging is fine since it doesn't interfere with HTTP responses.
2452 
2453 ### Best Practices
2454 
2455 * Use `log.Println()` (which defaults to stderr) or a logging library that writes to stderr or files.
2456 * Use `fmt.Fprintf(os.Stderr, ...)` to write to stderr explicitly.
2457 
2458 ### Quick Examples
2459 
2460 ```go theme={null}
2461 // ❌ Bad (STDIO)
2462 fmt.Println("Processing request")
2463 
2464 // ✅ Good (STDIO)
2465 log.Println("Processing request") // defaults to stderr
2466 
2467 // ✅ Good (STDIO)
2468 fmt.Fprintln(os.Stderr, "Processing request")
2469 ```
2470 
2471 ### System requirements
2472 
2473 * Go 1.24 or higher installed.
2474 
2475 ### Set up your environment
2476 
2477 First, let's install Go if you haven't already. You can download and install Go from [go.dev](https://go.dev/dl/).
2478 
2479 Verify your Go installation:
2480 
2481 ```bash theme={null}
2482 go version
2483 ```
2484 
2485 Now, let's create and set up our project:
2486 
2487 <CodeGroup>
2488 ```bash macOS/Linux theme={null}
2489 # Create a new directory for our project
2490 mkdir weather
2491 cd weather
2492 
2493 # Initialize Go module
2494 go mod init weather
2495 
2496 # Install dependencies
2497 go get github.com/modelcontextprotocol/go-sdk/mcp
2498 
2499 # Create our server file
2500 touch main.go
2501 ```
2502 
2503 ```powershell Windows theme={null}
2504 # Create a new directory for our project
2505 md weather
2506 cd weather
2507 
2508 # Initialize Go module
2509 go mod init weather
2510 
2511 # Install dependencies
2512 go get github.com/modelcontextprotocol/go-sdk/mcp
2513 
2514 # Create our server file
2515 new-item main.go
2516 ```
2517 </CodeGroup>
2518 
2519 Now let's dive into building your server.
2520 
2521 ## Building your server
2522 
2523 ### Importing packages and constants
2524 
2525 Add these to the top of your `main.go`:
2526 
2527 ```go theme={null}
2528 package main
2529 
2530 import (
2531 "cmp"
2532 "context"
2533 "encoding/json"
2534 "fmt"
2535 "io"
2536 "log"
2537 "net/http"
2538 "strings"
2539 
2540 "github.com/modelcontextprotocol/go-sdk/mcp"
2541 )
2542 
2543 const (
2544 NWSAPIBase = "https://api.weather.gov"
2545 UserAgent = "weather-app/1.0"
2546 )
2547 ```
2548 
2549 ### Data structures
2550 
2551 Next, let's define the data structures used by our tools:
2552 
2553 ```go theme={null}
2554 type PointsResponse struct {
2555 Properties struct {
2556 Forecast string `json:"forecast"`
2557 } `json:"properties"`
2558 }
2559 
2560 type ForecastResponse struct {
2561 Properties struct {
2562 Periods []ForecastPeriod `json:"periods"`
2563 } `json:"properties"`
2564 }
2565 
2566 type ForecastPeriod struct {
2567 Name string `json:"name"`
2568 Temperature int `json:"temperature"`
2569 TemperatureUnit string `json:"temperatureUnit"`
2570 WindSpeed string `json:"windSpeed"`
2571 WindDirection string `json:"windDirection"`
2572 DetailedForecast string `json:"detailedForecast"`
2573 }
2574 
2575 type AlertsResponse struct {
2576 Features []AlertFeature `json:"features"`
2577 }
2578 
2579 type AlertFeature struct {
2580 Properties AlertProperties `json:"properties"`
2581 }
2582 
2583 type AlertProperties struct {
2584 Event string `json:"event"`
2585 AreaDesc string `json:"areaDesc"`
2586 Severity string `json:"severity"`
2587 Description string `json:"description"`
2588 Instruction string `json:"instruction"`
2589 }
2590 
2591 type ForecastInput struct {
2592 Latitude float64 `json:"latitude" jsonschema:"Latitude of the location"`
2593 Longitude float64 `json:"longitude" jsonschema:"Longitude of the location"`
2594 }
2595 
2596 type AlertsInput struct {
2597 State string `json:"state" jsonschema:"Two-letter US state code (e.g. CA, NY)"`
2598 }
2599 ```
2600 
2601 ### Helper functions
2602 
2603 Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
2604 
2605 ```go theme={null}
2606 func makeNWSRequest[T any](ctx context.Context, url string) (*T, error) {
2607 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
2608 if err != nil {
2609 return nil, fmt.Errorf("failed to create request: %w", err)
2610 }
2611 
2612 req.Header.Set("User-Agent", UserAgent)
2613 req.Header.Set("Accept", "application/geo+json")
2614 
2615 client := http.DefaultClient
2616 resp, err := client.Do(req)
2617 if err != nil {
2618 return nil, fmt.Errorf("failed to make request to %s: %w", url, err)
2619 }
2620 defer resp.Body.Close()
2621 
2622 if resp.StatusCode != http.StatusOK {
2623 body, _ := io.ReadAll(resp.Body)
2624 return nil, fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body))
2625 }
2626 
2627 var result T
2628 if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
2629 return nil, fmt.Errorf("failed to decode response: %w", err)
2630 }
2631 
2632 return &result, nil
2633 }
2634 
2635 func formatAlert(alert AlertFeature) string {
2636 props := alert.Properties
2637 event := cmp.Or(props.Event, "Unknown")
2638 areaDesc := cmp.Or(props.AreaDesc, "Unknown")
2639 severity := cmp.Or(props.Severity, "Unknown")
2640 description := cmp.Or(props.Description, "No description available")
2641 instruction := cmp.Or(props.Instruction, "No specific instructions provided")
2642 
2643 return fmt.Sprintf(`
2644 Event: %s
2645 Area: %s
2646 Severity: %s
2647 Description: %s
2648 Instructions: %s
2649 `, event, areaDesc, severity, description, instruction)
2650 }
2651 
2652 func formatPeriod(period ForecastPeriod) string {
2653 return fmt.Sprintf(`
2654 %s:
2655 Temperature: %d°%s
2656 Wind: %s %s
2657 Forecast: %s
2658 `, period.Name, period.Temperature, period.TemperatureUnit,
2659 period.WindSpeed, period.WindDirection, period.DetailedForecast)
2660 }
2661 ```
2662 
2663 ### Implementing tool execution
2664 
2665 The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
2666 
2667 ```go theme={null}
2668 func getForecast(ctx context.Context, req *mcp.CallToolRequest, input ForecastInput) (
2669 *mcp.CallToolResult, any, error,
2670 ) {
2671 // Get points data
2672 pointsURL := fmt.Sprintf("%s/points/%f,%f", NWSAPIBase, input.Latitude, input.Longitude)
2673 pointsData, err := makeNWSRequest[PointsResponse](ctx, pointsURL)
2674 if err != nil {
2675 return &mcp.CallToolResult{
2676 Content: []mcp.Content{
2677 &mcp.TextContent{Text: "Unable to fetch forecast data for this location."},
2678 },
2679 }, nil, nil
2680 }
2681 
2682 // Get forecast data
2683 forecastURL := pointsData.Properties.Forecast
2684 if forecastURL == "" {
2685 return &mcp.CallToolResult{
2686 Content: []mcp.Content{
2687 &mcp.TextContent{Text: "Unable to fetch forecast URL."},
2688 },
2689 }, nil, nil
2690 }
2691 
2692 forecastData, err := makeNWSRequest[ForecastResponse](ctx, forecastURL)
2693 if err != nil {
2694 return &mcp.CallToolResult{
2695 Content: []mcp.Content{
2696 &mcp.TextContent{Text: "Unable to fetch detailed forecast."},
2697 },
2698 }, nil, nil
2699 }
2700 
2701 // Format the periods
2702 periods := forecastData.Properties.Periods
2703 if len(periods) == 0 {
2704 return &mcp.CallToolResult{
2705 Content: []mcp.Content{
2706 &mcp.TextContent{Text: "No forecast periods available."},
2707 },
2708 }, nil, nil
2709 }
2710 
2711 // Show next 5 periods
2712 var forecasts []string
2713 for i := range min(5, len(periods)) {
2714 forecasts = append(forecasts, formatPeriod(periods[i]))
2715 }
2716 
2717 result := strings.Join(forecasts, "\n---\n")
2718 
2719 return &mcp.CallToolResult{
2720 Content: []mcp.Content{
2721 &mcp.TextContent{Text: result},
2722 },
2723 }, nil, nil
2724 }
2725 
2726 func getAlerts(ctx context.Context, req *mcp.CallToolRequest, input AlertsInput) (
2727 *mcp.CallToolResult, any, error,
2728 ) {
2729 // Build alerts URL
2730 stateCode := strings.ToUpper(input.State)
2731 alertsURL := fmt.Sprintf("%s/alerts/active/area/%s", NWSAPIBase, stateCode)
2732 
2733 alertsData, err := makeNWSRequest[AlertsResponse](ctx, alertsURL)
2734 if err != nil {
2735 return &mcp.CallToolResult{
2736 Content: []mcp.Content{
2737 &mcp.TextContent{Text: "Unable to fetch alerts or no alerts found."},
2738 },
2739 }, nil, nil
2740 }
2741 
2742 // Check if there are any alerts
2743 if len(alertsData.Features) == 0 {
2744 return &mcp.CallToolResult{
2745 Content: []mcp.Content{
2746 &mcp.TextContent{Text: "No active alerts for this state."},
2747 },
2748 }, nil, nil
2749 }
2750 
2751 // Format alerts
2752 var alerts []string
2753 for _, feature := range alertsData.Features {
2754 alerts = append(alerts, formatAlert(feature))
2755 }
2756 
2757 result := strings.Join(alerts, "\n---\n")
2758 
2759 return &mcp.CallToolResult{
2760 Content: []mcp.Content{
2761 &mcp.TextContent{Text: result},
2762 },
2763 }, nil, nil
2764 }
2765 ```
2766 
2767 ### Running the server
2768 
2769 Finally, implement the main function to run the server:
2770 
2771 ```go theme={null}
2772 func main() {
2773 // Create MCP server
2774 server := mcp.NewServer(&mcp.Implementation{
2775 Name: "weather",
2776 Version: "1.0.0",
2777 }, nil)
2778 
2779 // Add get_forecast tool
2780 mcp.AddTool(server, &mcp.Tool{
2781 Name: "get_forecast",
2782 Description: "Get weather forecast for a location",
2783 }, getForecast)
2784 
2785 // Add get_alerts tool
2786 mcp.AddTool(server, &mcp.Tool{
2787 Name: "get_alerts",
2788 Description: "Get weather alerts for a US state",
2789 }, getAlerts)
2790 
2791 // Run server on stdio transport
2792 if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil {
2793 log.Fatal(err)
2794 }
2795 }
2796 ```
2797 
2798 Build your server with:
2799 
2800 ```bash theme={null}
2801 go build -o weather .
2802 ```
2803 
2804 The compiled binary will be in `./weather`.
2805 
2806 Let's now test your server from an existing MCP host, Claude for Desktop.
2807 
2808 ## Testing your server with Claude for Desktop
2809 
2810 First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
2811 
2812 We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
2813 
2814 For example, if you have [VS Code](https://code.visualstudio.com/) installed:
2815 
2816 <CodeGroup>
2817 ```bash Linux theme={null}
2818 code ~/.config/Claude/claude_desktop_config.json
2819 ```
2820 
2821 ```bash macOS theme={null}
2822 code ~/Library/Application\ Support/Claude/claude_desktop_config.json
2823 ```
2824 
2825 ```powershell Windows theme={null}
2826 code $env:AppData\Claude\claude_desktop_config.json
2827 ```
2828 </CodeGroup>
2829 
2830 You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
2831 
2832 In this case, we'll add our single weather server like so:
2833 
2834 <CodeGroup>
2835 ```json macOS/Linux theme={null}
2836 {
2837 "mcpServers": {
2838 "weather": {
2839 "command": "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/weather"
2840 }
2841 }
2842 }
2843 ```
2844 
2845 ```json Windows theme={null}
2846 {
2847 "mcpServers": {
2848 "weather": {
2849 "command": "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\weather.exe"
2850 }
2851 }
2852 }
2853 ```
2854 </CodeGroup>
2855 
2856 <Note>
2857 Make sure you pass in the absolute path to your compiled binary. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt from your project directory. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path, and add the `.exe` extension.
2858 </Note>
2859 
2860 This tells Claude for Desktop:
2861 
2862 1. There's an MCP server named "weather"
2863 2. Launch it by running the compiled binary at the specified path
2864 
2865 Save the file, and restart **Claude for Desktop**.
2866 </Tab>
2867</Tabs>
2796 }
2797}
2798```
2799 
2800> [!NOTE]
2801>
2802> Make sure you pass in the absolute path to your compiled binary. You can get this by running `pwd` on macOS/Linux or `cd` on Windows Command Prompt from your project directory. On Windows, remember to use double backslashes (`\\`) or forward slashes (`/`) in the JSON path, and add the `.exe` extension.
2803 
2804This tells Claude for Desktop:
2805 
28061. There's an MCP server named "weather"
28072. Launch it by running the compiled binary at the specified path
2808 
2809Save the file, and restart **Claude for Desktop**.
28682810 
28692811### Test with commands
28702812 
2871Let's make sure Claude for Desktop is picking up the two tools we've exposed in our `weather` server. You can do this by looking for the "Add files, connectors, and more /" <img src="https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/claude-add-files-connectors-and-more.png?fit=max&auto=format&n=cpXzQjUOzyH0mCNH&q=85&s=53acf21f6807dd5323b70b84b5d98d8a" style={{display: 'inline', margin: 0, height: '1.3em', width: 'auto'}} width="33" height="33" data-path="images/claude-add-files-connectors-and-more.png" /> icon:
2872 
2873<Frame>
2874 <img src="https://mintcdn.com/mcp/zNouQwo2h8cbxlDS/images/visual-indicator-mcp-tools.png?fit=max&auto=format&n=zNouQwo2h8cbxlDS&q=85&s=1bf23a2cfc5f6dd3dac1c7574cceebc9" width="684" height="133" data-path="images/visual-indicator-mcp-tools.png" />
2875</Frame>
2813Let's make sure Claude for Desktop is picking up the two tools we've exposed in our `weather` server. You can do this by looking for the "Add files, connectors, and more /" ![](https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/claude-add-files-connectors-and-more.png?fit=max\&auto=format\&n=cpXzQjUOzyH0mCNH\&q=85\&s=53acf21f6807dd5323b70b84b5d98d8a) icon:
2814 
2815![](https://mintcdn.com/mcp/zNouQwo2h8cbxlDS/images/visual-indicator-mcp-tools.png?fit=max\&auto=format\&n=zNouQwo2h8cbxlDS\&q=85\&s=1bf23a2cfc5f6dd3dac1c7574cceebc9)
28762816 
28772817After clicking on the plus icon, hover over the "Connectors" menu. You should see the `weather` servers listed:
28782818 
2879<Frame>
2880 <img src="https://mintcdn.com/mcp/zNouQwo2h8cbxlDS/images/available-mcp-tools.png?fit=max&auto=format&n=zNouQwo2h8cbxlDS&q=85&s=e2ace1ac88895a5fe30ebd8d01456bc3" width="437" height="244" data-path="images/available-mcp-tools.png" />
2881</Frame>
2819![](https://mintcdn.com/mcp/zNouQwo2h8cbxlDS/images/available-mcp-tools.png?fit=max\&auto=format\&n=zNouQwo2h8cbxlDS\&q=85\&s=e2ace1ac88895a5fe30ebd8d01456bc3)
28822820 
28832821If your server isn't being picked up by Claude for Desktop, proceed to the [Troubleshooting](#troubleshooting) section for debugging tips.
28842822 
from line 2825
28872825* What's the weather in Sacramento?
28882826* What are the active weather alerts in Texas?
28892827 
2890<Frame>
2891 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/current-weather.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=dce7b2f8a06c20ba358e4bd2e75fa4c7" width="2780" height="1849" data-path="images/current-weather.png" />
2892</Frame>
2893 
2894<Frame>
2895 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/weather-alerts.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=c4762bf2bd84a8781846d2965af3e4a4" width="2809" height="1850" data-path="images/weather-alerts.png" />
2896</Frame>
2897 
2898<Note>
2899 Since this is the US National Weather service, the queries will only work for US locations.
2900</Note>
2828![](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/current-weather.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=dce7b2f8a06c20ba358e4bd2e75fa4c7)
2829 
2830![](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/weather-alerts.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=c4762bf2bd84a8781846d2965af3e4a4)
2831 
2832> [!NOTE]
2833>
2834> Since this is the US National Weather service, the queries will only work for US locations.
29012835 
29022836## What's happening under the hood
29032837 
from line 2846
29122846 
29132847## Troubleshooting
29142848 
2915<AccordionGroup>
2916 <Accordion title="Claude for Desktop Integration Issues">
2917 **Getting logs from Claude for Desktop**
2918 
2919 Claude.app logging related to MCP is written to log files in `~/Library/Logs/Claude` (macOS) or `~/.config/Claude/logs/` (Linux):
2920 
2921 * `mcp.log` will contain general logging about MCP connections and connection failures.
2922 * Files named `mcp-server-SERVERNAME.log` will contain the stderr output from the named server. Stdio servers may use stderr for all their logging, so these files are not limited to errors.
2923 
2924 You can run the following command to list recent logs and follow along with any new ones:
2925 
2926 ```bash macOS theme={null}
2927 # Check Claude's logs for errors
2928 tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
2929 ```
2930 
2931 ```bash Linux theme={null}
2932 # Check Claude's logs for errors
2933 tail -n 20 -f ~/.config/Claude/logs/mcp*.log
2934 ```
2935 
2936 **Server not showing up in Claude**
2937 
2938 1. Check your `claude_desktop_config.json` file syntax
2939 2. Make sure the path to your project is absolute and not relative
2940 3. Restart Claude for Desktop completely
2941 
2942 <Warning>
2943 To properly restart Claude for Desktop, you must fully quit the application:
2944 
2945 * **Windows**: Right-click the Claude icon in the system tray (which may be hidden in the "hidden icons" menu) and select "Quit" or "Exit".
2946 * **macOS**: Use Cmd+Q or select "Quit Claude" from the menu bar.
2947 * **Linux**: Right-click the Claude icon in the system tray and select "Quit", or run `pkill -f claude-desktop` from a terminal.
2948 
2949 Simply closing the window does not fully quit the application, and your MCP server configuration changes will not take effect.
2950 </Warning>
2951 
2952 **Tool calls failing silently**
2953 
2954 If Claude attempts to use the tools but they fail:
2955 
2956 1. Check Claude's logs for errors
2957 2. Verify your server builds and runs without errors
2958 3. Try restarting Claude for Desktop
2959 
2960 **None of this is working. What do I do?**
2961 
2962 Please refer to our [debugging guide](/docs/2026-07-28/tools/debugging) for better debugging tools and more detailed guidance.
2963 </Accordion>
2964 
2965 <Accordion title="Weather API Issues">
2966 **Error: Failed to retrieve grid point data**
2967 
2968 This usually means either:
2969 
2970 1. The coordinates are outside the US
2971 2. The NWS API is having issues
2972 3. You're being rate limited
2973 
2974 Fix:
2975 
2976 * Verify you're using US coordinates
2977 * Add a small delay between requests
2978 * Check the NWS API status page
2979 
2980 **Error: No active alerts for \[STATE]**
2981 
2982 This isn't an error - it just means there are no current weather alerts for that state. Try a different state or check during severe weather.
2983 </Accordion>
2984</AccordionGroup>
2985 
2986<Note>
2987 For more advanced troubleshooting, check out our guide on [Debugging MCP](/docs/2026-07-28/tools/debugging)
2988</Note>
2849> **Claude for Desktop Integration Issues**
2850>
2851> **Getting logs from Claude for Desktop**
2852>
2853> Claude.app logging related to MCP is written to log files in `~/Library/Logs/Claude` (macOS) or `~/.config/Claude/logs/` (Linux):
2854>
2855> * `mcp.log` will contain general logging about MCP connections and connection failures.
2856> * Files named `mcp-server-SERVERNAME.log` will contain the stderr output from the named server. Stdio servers may use stderr for all their logging, so these files are not limited to errors.
2857>
2858> You can run the following command to list recent logs and follow along with any new ones:
2859>
2860> ```bash macOS theme={null}
2861> # Check Claude's logs for errors
2862> tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
2863> ```
2864>
2865> ```bash Linux theme={null}
2866> # Check Claude's logs for errors
2867> tail -n 20 -f ~/.config/Claude/logs/mcp*.log
2868> ```
2869>
2870> **Server not showing up in Claude**
2871>
2872> 1. Check your `claude_desktop_config.json` file syntax
2873>
2874> 2. Make sure the path to your project is absolute and not relative
2875>
2876> 3. Restart Claude for Desktop completely
2877>
2878> > [!WARNING]
2879> >
2880> > To properly restart Claude for Desktop, you must fully quit the application:
2881> >
2882> > * **Windows**: Right-click the Claude icon in the system tray (which may be hidden in the "hidden icons" menu) and select "Quit" or "Exit".
2883> > * **macOS**: Use Cmd+Q or select "Quit Claude" from the menu bar.
2884> > * **Linux**: Right-click the Claude icon in the system tray and select "Quit", or run `pkill -f claude-desktop` from a terminal.
2885> >
2886> > Simply closing the window does not fully quit the application, and your MCP server configuration changes will not take effect.
2887>
2888> **Tool calls failing silently**
2889>
2890> If Claude attempts to use the tools but they fail:
2891>
2892> 1. Check Claude's logs for errors
2893> 2. Verify your server builds and runs without errors
2894> 3. Try restarting Claude for Desktop
2895>
2896> **None of this is working. What do I do?**
2897>
2898> Please refer to our [debugging guide](/docs/2026-07-28/tools/debugging) for better debugging tools and more detailed guidance.
2899 
2900> **Weather API Issues**
2901>
2902> **Error: Failed to retrieve grid point data**
2903>
2904> This usually means either:
2905>
2906> 1. The coordinates are outside the US
2907> 2. The NWS API is having issues
2908> 3. You're being rate limited
2909>
2910> Fix:
2911>
2912> * Verify you're using US coordinates
2913> * Add a small delay between requests
2914> * Check the NWS API status page
2915>
2916> **Error: No active alerts for \[STATE]**
2917>
2918> This isn't an error - it just means there are no current weather alerts for that state. Try a different state or check during severe weather.
2919 
2920> [!NOTE]
2921>
2922> For more advanced troubleshooting, check out our guide on [Debugging MCP](/docs/2026-07-28/tools/debugging)
29892923 
29902924## Next steps
29912925 
2992<CardGroup cols={2}>
2993 <Card title="Building a client" icon="outlet" href="/docs/2026-07-28/develop/build-client">
2994 Learn how to build your own MCP client that can connect to your server
2995 </Card>
2996 
2997 <Card title="Example servers" icon="grid" href="/examples">
2998 Check out our gallery of official MCP servers and implementations
2999 </Card>
3000 
3001 <Card title="Debugging Guide" icon="bug" href="/docs/2026-07-28/tools/debugging">
3002 Learn how to effectively debug MCP servers and integrations
3003 </Card>
3004 
3005 <Card title="Build with Agent Skills" icon="comments" href="/docs/2026-07-28/develop/build-with-agent-skills">
3006 Use agent skills to guide AI coding assistants through server design
3007 </Card>
3008</CardGroup>
2926> **[Building a client](/docs/2026-07-28/develop/build-client)**
2927>
2928> Learn how to build your own MCP client that can connect to your server
2929 
2930> **[Example servers](/examples)**
2931>
2932> Check out our gallery of official MCP servers and implementations
2933 
2934> **[Debugging Guide](/docs/2026-07-28/tools/debugging)**
2935>
2936> Learn how to effectively debug MCP servers and integrations
2937 
2938> **[Build with Agent Skills](/docs/2026-07-28/develop/build-with-agent-skills)**
2939>
2940> Use agent skills to guide AI coding assistants through server design
30092941 

docs/2026-07-28/develop/build-with-agent-skills Changed · +9 / -11 lines

from line 85
8585Once your agent scaffolds the server, iterate on tool descriptions and error
8686handling, then test and ship:
8787 
88<CardGroup cols={2}>
89 <Card title="MCP Inspector" icon="magnifying-glass" href="/docs/2026-07-28/tools/inspector">
90 Test your server's tools, resources, and prompts interactively
91 </Card>
88> **[MCP Inspector](/docs/2026-07-28/tools/inspector)**
89>
90> Test your server's tools, resources, and prompts interactively
9291 
93 <Card title="Connect to a client" icon="plug" href="/docs/2026-07-28/develop/connect-local-servers">
94 Wire your server into an MCP client via local or remote configuration
95 </Card>
92> **[Connect to a client](/docs/2026-07-28/develop/connect-local-servers)**
93>
94> Wire your server into an MCP client via local or remote configuration
9695 
97 <Card title="Publish to the Registry" icon="box" href="/registry/quickstart">
98 Make your server discoverable in the MCP Registry
99 </Card>
100</CardGroup>
96> **[Publish to the Registry](/registry/quickstart)**
97>
98> Make your server discoverable in the MCP Registry
10199 

docs/2026-07-28/develop/connect-local-servers Changed · +188 / -212 lines

from line 6
66 
77This guide demonstrates how to connect to local MCP servers using Claude Desktop as an example, one of the many clients that support MCP. While we focus on Claude Desktop's implementation, the concepts apply broadly to other MCP-compatible clients. By the end of this tutorial, Claude will be able to interact with files on your computer, create new documents, organize folders, and search through your file system—all with your explicit permission for each action.
88 
9<Frame>
10 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-filesystem.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=629d7e754dc358d71a408d6ce970c1b1" alt="Claude Desktop with filesystem integration showing file management capabilities" width="1732" height="2060" data-path="images/quickstart-filesystem.png" />
11</Frame>
9![Claude Desktop with filesystem integration showing file management capabilities](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-filesystem.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=629d7e754dc358d71a408d6ce970c1b1)
1210 
1311## Prerequisites
1412 
from line 43
4543 
4644The process involves configuring Claude Desktop to automatically start the Filesystem Server whenever you launch the application. This configuration is done through a JSON file that tells Claude Desktop which servers to run and how to connect to them.
4745 
48<Steps>
49 <Step title="Open Claude Desktop Settings">
50 Start by accessing the Claude Desktop settings. Click on the Claude menu in your system's menu bar (not the settings within the Claude window itself) and select "Settings..."
46**1. Open Claude Desktop Settings**
5147 
52 On macOS, this appears in the top menu bar:
48Start by accessing the Claude Desktop settings. Click on the Claude menu in your system's menu bar (not the settings within the Claude window itself) and select "Settings..."
5349 
54 <Frame style={{ textAlign: "center" }}>
55 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-menu.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=0c8b57e0e17af3624b6762a3ea944c8e" width="400" alt="Claude Desktop menu showing Settings option" data-path="images/quickstart-menu.png" />
56 </Frame>
50On macOS, this appears in the top menu bar:
5751 
58 This opens the Claude Desktop configuration window, which is separate from your Claude account settings.
59 </Step>
52![Claude Desktop menu showing Settings option](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-menu.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=0c8b57e0e17af3624b6762a3ea944c8e)
6053 
61 <Step title="Access Developer Settings">
62 In the Settings window, navigate to the "Developer" tab in the left sidebar. This section contains options for configuring MCP servers and other developer features.
54This opens the Claude Desktop configuration window, which is separate from your Claude account settings.
6355 
64 Click the "Edit Config" button to open the configuration file:
56**2. Access Developer Settings**
6557 
66 <Frame>
67 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-developer.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=0fb595490a2f9e15c0301e771a57446c" alt="Developer settings showing Edit Config button" width="1688" height="534" data-path="images/quickstart-developer.png" />
68 </Frame>
58In the Settings window, navigate to the "Developer" tab in the left sidebar. This section contains options for configuring MCP servers and other developer features.
6959 
70 This action creates a new configuration file if one doesn't exist, or opens your existing configuration. The file is located at:
60Click the "Edit Config" button to open the configuration file:
7161 
72 * **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
73 * **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
74 </Step>
62![Developer settings showing Edit Config button](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-developer.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=0fb595490a2f9e15c0301e771a57446c)
7563 
76 <Step title="Configure the Filesystem Server">
77 Replace the contents of the configuration file with the following JSON structure. This configuration tells Claude Desktop to start the Filesystem Server with access to specific directories:
64This action creates a new configuration file if one doesn't exist, or opens your existing configuration. The file is located at:
7865 
79 <CodeGroup>
80 ```json macOS theme={null}
81 {
82 "mcpServers": {
83 "filesystem": {
84 "command": "npx",
85 "args": [
86 "-y",
87 "@modelcontextprotocol/server-filesystem",
88 "/Users/username/Desktop",
89 "/Users/username/Downloads"
90 ]
91 }
92 }
93 }
94 ```
66* **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
67* **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
9568 
96 ```json Windows theme={null}
97 {
98 "mcpServers": {
99 "filesystem": {
100 "command": "npx",
101 "args": [
102 "-y",
103 "@modelcontextprotocol/server-filesystem",
104 "C:\\Users\\username\\Desktop",
105 "C:\\Users\\username\\Downloads"
106 ]
107 }
108 }
109 }
110 ```
111 </CodeGroup>
69**3. Configure the Filesystem Server**
11270 
113 Replace `username` with your actual computer username. The paths listed in the `args` array specify which directories the Filesystem Server can access. You can modify these paths or add additional directories as needed.
71Replace the contents of the configuration file with the following JSON structure. This configuration tells Claude Desktop to start the Filesystem Server with access to specific directories:
11472 
115 <Tip>
116 **Understanding the Configuration**
73```json macOS theme={null}
74{
75 "mcpServers": {
76 "filesystem": {
77 "command": "npx",
78 "args": [
79 "-y",
80 "@modelcontextprotocol/server-filesystem",
81 "/Users/username/Desktop",
82 "/Users/username/Downloads"
83 ]
84 }
85 }
86}
87```
11788 
118 * `"filesystem"`: A friendly name for the server that appears in Claude Desktop
119 * `"command": "npx"`: Uses Node.js's npx tool to run the server
120 * `"-y"`: Automatically confirms the installation of the server package
121 * `"@modelcontextprotocol/server-filesystem"`: The package name of the Filesystem Server
122 * The remaining arguments: Directories the server is allowed to access
123 </Tip>
89```json Windows theme={null}
90{
91 "mcpServers": {
92 "filesystem": {
93 "command": "npx",
94 "args": [
95 "-y",
96 "@modelcontextprotocol/server-filesystem",
97 "C:\\Users\\username\\Desktop",
98 "C:\\Users\\username\\Downloads"
99 ]
100 }
101 }
102}
103```
124104 
125 <Warning>
126 **Security Consideration**
105Replace `username` with your actual computer username. The paths listed in the `args` array specify which directories the Filesystem Server can access. You can modify these paths or add additional directories as needed.
127106 
128 Only grant access to directories you're comfortable with Claude reading and modifying. The server runs with your user account permissions, so it can perform any file operations you can perform manually.
129 </Warning>
130 </Step>
107> [!TIP]
108>
109> **Understanding the Configuration**
110>
111> * `"filesystem"`: A friendly name for the server that appears in Claude Desktop
112> * `"command": "npx"`: Uses Node.js's npx tool to run the server
113> * `"-y"`: Automatically confirms the installation of the server package
114> * `"@modelcontextprotocol/server-filesystem"`: The package name of the Filesystem Server
115> * The remaining arguments: Directories the server is allowed to access
131116 
132 <Step title="Restart Claude Desktop">
133 After saving the configuration file, completely quit Claude Desktop and restart it. The application needs to restart to load the new configuration and start the MCP server.
117> [!WARNING]
118>
119> **Security Consideration**
120>
121> Only grant access to directories you're comfortable with Claude reading and modifying. The server runs with your user account permissions, so it can perform any file operations you can perform manually.
134122 
135 Upon successful restart, click the "Add files, connectors, and more /" indicator <img src="https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/claude-add-files-connectors-and-more.png?fit=max&auto=format&n=cpXzQjUOzyH0mCNH&q=85&s=53acf21f6807dd5323b70b84b5d98d8a" style={{display: 'inline', margin: 0, height: '1.3em', width: 'auto'}} width="33" height="33" data-path="images/claude-add-files-connectors-and-more.png" /> in the bottom-left corner of the conversation input box:
123**4. Restart Claude Desktop**
136124 
137 <Frame>
138 <img src="https://mintcdn.com/mcp/akpggzunDlIcY2im/images/quickstart-slider.png?fit=max&auto=format&n=akpggzunDlIcY2im&q=85&s=a1ebd4259cff2a7472171885f2edc035" alt="Claude Desktop interface showing MCP server indicator" width="1414" height="410" data-path="images/quickstart-slider.png" />
139 </Frame>
125After saving the configuration file, completely quit Claude Desktop and restart it. The application needs to restart to load the new configuration and start the MCP server.
140126 
141 Click on this indicator, then move the mouse over "Connectors" and click "Manage connectors". Select "filesystem" from the connector list to view the Filesystem Server's available tools:
127Upon successful restart, click the "Add files, connectors, and more /" indicator ![](https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/claude-add-files-connectors-and-more.png?fit=max\&auto=format\&n=cpXzQjUOzyH0mCNH\&q=85\&s=53acf21f6807dd5323b70b84b5d98d8a) in the bottom-left corner of the conversation input box:
142128 
143 <Frame style={{ textAlign: "center" }}>
144 <img src="https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-tools.png?fit=max&auto=format&n=cpXzQjUOzyH0mCNH&q=85&s=212a63d76daba170d52db0d2f6f582be" width="400" alt="Available filesystem tools in Claude Desktop" data-path="images/quickstart-tools.png" />
145 </Frame>
129![Claude Desktop interface showing MCP server indicator](https://mintcdn.com/mcp/akpggzunDlIcY2im/images/quickstart-slider.png?fit=max\&auto=format\&n=akpggzunDlIcY2im\&q=85\&s=a1ebd4259cff2a7472171885f2edc035)
146130 
147 If the Filesystem Server doesn't connect, refer to the [Troubleshooting](#troubleshooting) section for debugging steps.
148 </Step>
149</Steps>
131Click on this indicator, then move the mouse over "Connectors" and click "Manage connectors". Select "filesystem" from the connector list to view the Filesystem Server's available tools:
150132 
133![Available filesystem tools in Claude Desktop](https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-tools.png?fit=max\&auto=format\&n=cpXzQjUOzyH0mCNH\&q=85\&s=212a63d76daba170d52db0d2f6f582be)
134 
135If the Filesystem Server doesn't connect, refer to the [Troubleshooting](#troubleshooting) section for debugging steps.
136 
151137## Using the Filesystem Server
152138 
153139With the Filesystem Server connected, Claude can now interact with your file system. Try these example requests to explore the capabilities:
from line 148
162148 
163149Before executing any file system operation, Claude will request your approval. This ensures you maintain control over all actions:
164150 
165<Frame style={{ textAlign: "center" }}>
166 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-approve.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=98cc6e9dfe885fbd6e9bfae40601e494" width="500" alt="Claude requesting approval to perform a file operation" data-path="images/quickstart-approve.png" />
167</Frame>
151![Claude requesting approval to perform a file operation](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-approve.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=98cc6e9dfe885fbd6e9bfae40601e494)
168152 
169153Review each request carefully before approving. You can always deny a request if you're not comfortable with the proposed action.
170154 
from line 156
172156 
173157If you encounter issues setting up or using the Filesystem Server, these solutions address common problems:
174158 
175<AccordionGroup>
176 <Accordion title="Server not showing up in Claude / hammer icon missing">
177 1. Restart Claude Desktop completely
178 2. Check your `claude_desktop_config.json` file syntax
179 3. Make sure the file paths included in `claude_desktop_config.json` are valid and that they are absolute and not relative
180 4. Look at [logs](#getting-logs-from-claude-for-desktop) to see why the server is not connecting
181 5. In your command line, try manually running the server (replacing `username` as you did in `claude_desktop_config.json`) to see if you get any errors:
159> **Server not showing up in Claude / hammer icon missing**
160>
161> 1. Restart Claude Desktop completely
162> 2. Check your `claude_desktop_config.json` file syntax
163> 3. Make sure the file paths included in `claude_desktop_config.json` are valid and that they are absolute and not relative
164> 4. Look at [logs](#getting-logs-from-claude-for-desktop) to see why the server is not connecting
165> 5. In your command line, try manually running the server (replacing `username` as you did in `claude_desktop_config.json`) to see if you get any errors:
166>
167> ```bash macOS/Linux theme={null}
168> npx -y @modelcontextprotocol/server-filesystem /Users/username/Desktop /Users/username/Downloads
169> ```
170>
171> ```powershell Windows theme={null}
172> npx -y @modelcontextprotocol/server-filesystem C:\Users\username\Desktop C:\Users\username\Downloads
173> ```
182174 
183 <CodeGroup>
184 ```bash macOS/Linux theme={null}
185 npx -y @modelcontextprotocol/server-filesystem /Users/username/Desktop /Users/username/Downloads
186 ```
175> **Getting logs from Claude Desktop**
176>
177> Claude.app logging related to MCP is written to log files in:
178>
179> * macOS: `~/Library/Logs/Claude`
180>
181> * Windows: `%APPDATA%\Claude\logs`
182>
183> * `mcp.log` will contain general logging about MCP connections and connection failures.
184>
185> * Files named `mcp-server-SERVERNAME.log` will contain the stderr output from the named server. Stdio servers may use stderr for all their logging, so these files are not limited to errors.
186>
187> You can run the following command to list recent logs and follow along with any new ones (on Windows, it will only show recent logs):
188>
189> ```bash macOS/Linux theme={null}
190> tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
191> ```
192>
193> ```powershell Windows theme={null}
194> type "%APPDATA%\Claude\logs\mcp*.log"
195> ```
187196 
188 ```powershell Windows theme={null}
189 npx -y @modelcontextprotocol/server-filesystem C:\Users\username\Desktop C:\Users\username\Downloads
190 ```
191 </CodeGroup>
192 </Accordion>
197> **Tool calls failing silently**
198>
199> If Claude attempts to use the tools but they fail:
200>
201> 1. Check Claude's logs for errors
202> 2. Verify your server builds and runs without errors
203> 3. Try restarting Claude Desktop
193204 
194 <Accordion title="Getting logs from Claude Desktop">
195 Claude.app logging related to MCP is written to log files in:
205> **None of this is working. What do I do?**
206>
207> Please refer to our [debugging guide](/docs/2026-07-28/tools/debugging) for better debugging tools and more detailed guidance.
196208 
197 * macOS: `~/Library/Logs/Claude`
209> **ENOENT error and `$\{APPDATA\}` in paths on Windows**
210>
211> If your configured server fails to load, and you see within its logs an error referring to `${APPDATA}` within a path, you may need to add the expanded value of `%APPDATA%` to your `env` key in `claude_desktop_config.json`:
212>
213> ```json theme={null}
214> {
215> "brave-search": {
216> "command": "npx",
217> "args": ["-y", "@modelcontextprotocol/server-brave-search"],
218> "env": {
219> "APPDATA": "C:\\Users\\user\\AppData\\Roaming\\",
220> "BRAVE_API_KEY": "..."
221> }
222> }
223> }
224> ```
225>
226> With this change in place, launch Claude Desktop once again.
227>
228> > [!WARNING]
229> >
230> > **npm should be installed globally**
231> >
232> > The `npx` command may continue to fail if you have not installed npm globally. If npm is already installed globally, you will find `%APPDATA%\npm` exists on your system. If not, you can install npm globally by running the following command:
233> >
234> > ```bash theme={null}
235> > npm install -g npm
236> > ```
198237 
199 * Windows: `%APPDATA%\Claude\logs`
200 
201 * `mcp.log` will contain general logging about MCP connections and connection failures.
202 
203 * Files named `mcp-server-SERVERNAME.log` will contain the stderr output from the named server. Stdio servers may use stderr for all their logging, so these files are not limited to errors.
204 
205 You can run the following command to list recent logs and follow along with any new ones (on Windows, it will only show recent logs):
206 
207 <CodeGroup>
208 ```bash macOS/Linux theme={null}
209 tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
210 ```
211 
212 ```powershell Windows theme={null}
213 type "%APPDATA%\Claude\logs\mcp*.log"
214 ```
215 </CodeGroup>
216 </Accordion>
217 
218 <Accordion title="Tool calls failing silently">
219 If Claude attempts to use the tools but they fail:
220 
221 1. Check Claude's logs for errors
222 2. Verify your server builds and runs without errors
223 3. Try restarting Claude Desktop
224 </Accordion>
225 
226 <Accordion title="None of this is working. What do I do?">
227 Please refer to our [debugging guide](/docs/2026-07-28/tools/debugging) for better debugging tools and more detailed guidance.
228 </Accordion>
229 
230 <Accordion title="ENOENT error and `${APPDATA}` in paths on Windows">
231 If your configured server fails to load, and you see within its logs an error referring to `${APPDATA}` within a path, you may need to add the expanded value of `%APPDATA%` to your `env` key in `claude_desktop_config.json`:
232 
233 ```json theme={null}
234 {
235 "brave-search": {
236 "command": "npx",
237 "args": ["-y", "@modelcontextprotocol/server-brave-search"],
238 "env": {
239 "APPDATA": "C:\\Users\\user\\AppData\\Roaming\\",
240 "BRAVE_API_KEY": "..."
241 }
242 }
243 }
244 ```
245 
246 With this change in place, launch Claude Desktop once again.
247 
248 <Warning>
249 **npm should be installed globally**
250 
251 The `npx` command may continue to fail if you have not installed npm globally. If npm is already installed globally, you will find `%APPDATA%\npm` exists on your system. If not, you can install npm globally by running the following command:
252 
253 ```bash theme={null}
254 npm install -g npm
255 ```
256 </Warning>
257 </Accordion>
258</AccordionGroup>
259 
260238## Next Steps
261239 
262240Now that you've successfully connected Claude Desktop to a local MCP server, explore these options to expand your setup:
263241 
264<CardGroup cols={2}>
265 <Card title="Explore other servers" icon="grid" href="https://github.com/modelcontextprotocol/servers">
266 Browse our collection of official and community-created MCP servers for
267 additional capabilities
268 </Card>
242> **[Explore other servers](https://github.com/modelcontextprotocol/servers)**
243>
244> Browse our collection of official and community-created MCP servers for
245> additional capabilities
269246 
270 <Card title="Build your own server" icon="code" href="/docs/2026-07-28/develop/build-server">
271 Create custom MCP servers tailored to your specific workflows and
272 integrations
273 </Card>
247> **[Build your own server](/docs/2026-07-28/develop/build-server)**
248>
249> Create custom MCP servers tailored to your specific workflows and
250> integrations
274251 
275 <Card title="Connect to remote servers" icon="cloud" href="/docs/2026-07-28/develop/connect-remote-servers">
276 Learn how to connect Claude to remote MCP servers for cloud-based tools and
277 services
278 </Card>
252> **[Connect to remote servers](/docs/2026-07-28/develop/connect-remote-servers)**
253>
254> Learn how to connect Claude to remote MCP servers for cloud-based tools and
255> services
279256 
280 <Card title="Understand the protocol" icon="book" href="/docs/2026-07-28/learn/architecture">
281 Dive deeper into how MCP works and its architecture
282 </Card>
283</CardGroup>
257> **[Understand the protocol](/docs/2026-07-28/learn/architecture)**
258>
259> Dive deeper into how MCP works and its architecture
284260 

docs/2026-07-28/develop/connect-remote-servers Changed · +46 / -62 lines

from line 25
2525 
2626The process of connecting Claude to a remote MCP server involves adding a Custom Connector through the [Claude interface](https://claude.ai/). This establishes a secure connection between Claude and your chosen remote server.
2727 
28<Steps>
29 <Step title="Navigate to Connector Settings">
30 Open Claude Desktop or Claude in your browser, then navigate to the settings page:
28**1. Navigate to Connector Settings**
3129 
32 * **Desktop**: Either use the keyboard shortcut `Ctrl+Comma` or click the top-left menu icon <img src="https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/claude-desktop-hamburger-menu-icon.png?fit=max&auto=format&n=cpXzQjUOzyH0mCNH&q=85&s=66e498f668362c79f829a07b5ce863c8" style={{display: 'inline', margin: 0, height: '1.3em', width: 'auto'}} width="33" height="33" data-path="images/claude-desktop-hamburger-menu-icon.png" />, hover over "File", and select "Settings"
33 * **Browser**: Either use the keyboard shortcut `⌘⇧,` (*macOS*) or click on your profile icon, and select "Settings" from the menu
30Open Claude Desktop or Claude in your browser, then navigate to the settings page:
3431 
35 Once you're in the settings page, click "Connectors" in the sidebar. This displays your currently configured connectors and provides options for adding new ones.
36 </Step>
32* **Desktop**: Either use the keyboard shortcut `Ctrl+Comma` or click the top-left menu icon ![](https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/claude-desktop-hamburger-menu-icon.png?fit=max\&auto=format\&n=cpXzQjUOzyH0mCNH\&q=85\&s=66e498f668362c79f829a07b5ce863c8), hover over "File", and select "Settings"
33* **Browser**: Either use the keyboard shortcut `⌘⇧,` (*macOS*) or click on your profile icon, and select "Settings" from the menu
3734 
38 <Step title="Add a Custom Connector">
39 In the Connectors section, click the "Add" button at the top-right of the window, then select "Add custom connector" from the dropdown. This begins the connection process. To follow along, copy/paste the URL below:
35Once you're in the settings page, click "Connectors" in the sidebar. This displays your currently configured connectors and provides options for adding new ones.
4036 
41 ```text Example Remote Server theme={null}
42 https://example-server.modelcontextprotocol.io/mcp
43 ```
37**2. Add a Custom Connector**
4438 
45 <Frame>
46 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-remote/1-add-connector.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=b5ae9b23164875bbaa3aff4c178cdc64" alt="Add custom connector button in Claude settings" width="1038" height="809" data-path="images/quickstart-remote/1-add-connector.png" />
47 </Frame>
39In the Connectors section, click the "Add" button at the top-right of the window, then select "Add custom connector" from the dropdown. This begins the connection process. To follow along, copy/paste the URL below:
4840 
49 A dialog will appear prompting you to enter the remote MCP server URL. This URL should be provided by the server developer or administrator. Enter the complete URL, ensuring it includes the proper protocol (https\://) and any necessary path components.
41```text Example Remote Server theme={null}
42https://example-server.modelcontextprotocol.io/mcp
43```
5044 
51 <Frame>
52 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-remote/2-connect.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=0934f16d8e016cade8e560c8f89d011b" alt="Dialog for entering remote MCP server URL" width="1616" height="282" data-path="images/quickstart-remote/2-connect.png" />
53 </Frame>
45![Add custom connector button in Claude settings](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-remote/1-add-connector.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=b5ae9b23164875bbaa3aff4c178cdc64)
5446 
55 After entering the URL, click "Add" to proceed with the connection.
56 </Step>
47A dialog will appear prompting you to enter the remote MCP server URL. This URL should be provided by the server developer or administrator. Enter the complete URL, ensuring it includes the proper protocol (https\://) and any necessary path components.
5748 
58 <Step title="Complete Authentication">
59 Most remote MCP servers require authentication to ensure secure access to their resources. The authentication process varies depending on the server implementation but commonly involves OAuth, API keys, or username/password combinations.
49![Dialog for entering remote MCP server URL](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-remote/2-connect.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=0934f16d8e016cade8e560c8f89d011b)
6050 
61 <Frame>
62 <img src="https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-remote/3-auth.png?fit=max&auto=format&n=4ZXF1PrDkEaJvXpn&q=85&s=89af6e1b85718637231388697cc7b015" alt="Authentication screen for remote MCP server" width="490" height="806" data-path="images/quickstart-remote/3-auth.png" />
63 </Frame>
51After entering the URL, click "Add" to proceed with the connection.
6452 
65 Follow the authentication prompts provided by the server. This may redirect you to a third-party authentication provider or display a form within Claude. Once authentication is complete, Claude will establish a secure connection to the remote server.
66 </Step>
53**3. Complete Authentication**
6754 
68 <Step title="Access Resources and Prompts">
69 After successful connection, the remote server’s resources and prompts become available in your Claude conversations. You can access these by clicking the "Add files, connectors, and more /" indicator <img src="https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/claude-add-files-connectors-and-more.png?fit=max&auto=format&n=cpXzQjUOzyH0mCNH&q=85&s=53acf21f6807dd5323b70b84b5d98d8a" style={{display: 'inline', margin: 0, height: '1.3em', width: 'auto'}} width="33" height="33" data-path="images/claude-add-files-connectors-and-more.png" /> in the bottom-left corner of the message input area. Then hover over "Connectors", move the cursor over "Add to Example Remote Server", where hovering displays the attachment menu.
55Most remote MCP servers require authentication to ensure secure access to their resources. The authentication process varies depending on the server implementation but commonly involves OAuth, API keys, or username/password combinations.
7056 
71 <Frame>
72 <img src="https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-remote/4-select-resources-menu.png?fit=max&auto=format&n=cpXzQjUOzyH0mCNH&q=85&s=e5fa85174f8acbadbd709bac66f42d5c" alt="Attachment menu showing available resources" width="735" height="378" data-path="images/quickstart-remote/4-select-resources-menu.png" />
73 </Frame>
57![Authentication screen for remote MCP server](https://mintcdn.com/mcp/4ZXF1PrDkEaJvXpn/images/quickstart-remote/3-auth.png?fit=max\&auto=format\&n=4ZXF1PrDkEaJvXpn\&q=85\&s=89af6e1b85718637231388697cc7b015)
7458 
75 The menu displays all available resources and prompts from your connected server. Select the items you want to include in your conversation. These resources provide Claude with context and information from your external tools.
59Follow the authentication prompts provided by the server. This may redirect you to a third-party authentication provider or display a form within Claude. Once authentication is complete, Claude will establish a secure connection to the remote server.
7660 
77 <Frame>
78 <img src="https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-remote/5-select-prompts-resources.png?fit=max&auto=format&n=cpXzQjUOzyH0mCNH&q=85&s=68722669d9e18252756885c703e4f221" alt="Selecting specific resources and prompts from the menu" width="648" height="529" data-path="images/quickstart-remote/5-select-prompts-resources.png" />
79 </Frame>
80 </Step>
61**4. Access Resources and Prompts**
8162 
82 <Step title="Configure Tool Permissions">
83 Remote MCP servers often expose multiple tools with varying capabilities. You can control which tools Claude is allowed to use by configuring permissions in the connector settings. This ensures Claude only performs actions you've explicitly authorized.
63After successful connection, the remote server’s resources and prompts become available in your Claude conversations. You can access these by clicking the "Add files, connectors, and more /" indicator ![](https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/claude-add-files-connectors-and-more.png?fit=max\&auto=format\&n=cpXzQjUOzyH0mCNH\&q=85\&s=53acf21f6807dd5323b70b84b5d98d8a) in the bottom-left corner of the message input area. Then hover over "Connectors", move the cursor over "Add to Example Remote Server", where hovering displays the attachment menu.
8464 
85 <Frame>
86 <img src="https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-remote/6-configure-tools.png?fit=max&auto=format&n=cpXzQjUOzyH0mCNH&q=85&s=5cfd8b2c5d06e7e3699eac24c68d090e" alt="Tool permission configuration interface" width="604" height="745" data-path="images/quickstart-remote/6-configure-tools.png" />
87 </Frame>
65![Attachment menu showing available resources](https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-remote/4-select-resources-menu.png?fit=max\&auto=format\&n=cpXzQjUOzyH0mCNH\&q=85\&s=e5fa85174f8acbadbd709bac66f42d5c)
8866 
89 Navigate back to the Connectors settings and click on your connected server. Here you can enable or disable specific tools, set usage limits, and configure other security parameters according to your needs.
90 </Step>
91</Steps>
67The menu displays all available resources and prompts from your connected server. Select the items you want to include in your conversation. These resources provide Claude with context and information from your external tools.
9268 
69![Selecting specific resources and prompts from the menu](https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-remote/5-select-prompts-resources.png?fit=max\&auto=format\&n=cpXzQjUOzyH0mCNH\&q=85\&s=68722669d9e18252756885c703e4f221)
70 
71**5. Configure Tool Permissions**
72 
73Remote MCP servers often expose multiple tools with varying capabilities. You can control which tools Claude is allowed to use by configuring permissions in the connector settings. This ensures Claude only performs actions you've explicitly authorized.
74 
75![Tool permission configuration interface](https://mintcdn.com/mcp/cpXzQjUOzyH0mCNH/images/quickstart-remote/6-configure-tools.png?fit=max\&auto=format\&n=cpXzQjUOzyH0mCNH\&q=85\&s=5cfd8b2c5d06e7e3699eac24c68d090e)
76 
77Navigate back to the Connectors settings and click on your connected server. Here you can enable or disable specific tools, set usage limits, and configure other security parameters according to your needs.
78 
9379## Best Practices for Using Remote MCP Servers
9480 
9581When working with remote MCP servers, consider these recommendations to ensure a secure and efficient experience:
from line 88
10288 
10389Now that you've connected Claude to a remote MCP server, you can explore its capabilities in your conversations. Try using the connected tools to automate tasks, access external data, or integrate with your existing workflows.
10490 
105<CardGroup cols={2}>
106 <Card title="Build your own remote server" icon="cloud" href="/docs/2026-07-28/develop/build-server">
107 Create custom remote MCP servers to integrate with proprietary tools and
108 services
109 </Card>
91> **[Build your own remote server](/docs/2026-07-28/develop/build-server)**
92>
93> Create custom remote MCP servers to integrate with proprietary tools and
94> services
11095 
111 <Card title="Explore available servers" icon="grid" href="https://github.com/modelcontextprotocol/servers">
112 Browse our collection of official and community-created MCP servers
113 </Card>
96> **[Explore available servers](https://github.com/modelcontextprotocol/servers)**
97>
98> Browse our collection of official and community-created MCP servers
11499 
115 <Card title="Connect local servers" icon="computer" href="/docs/2026-07-28/develop/connect-local-servers">
116 Learn how to connect Claude Desktop to local MCP servers for direct system
117 access
118 </Card>
100> **[Connect local servers](/docs/2026-07-28/develop/connect-local-servers)**
101>
102> Learn how to connect Claude Desktop to local MCP servers for direct system
103> access
119104 
120 <Card title="Understand the architecture" icon="book" href="/docs/2026-07-28/learn/architecture">
121 Dive deeper into how MCP works and its architecture
122 </Card>
123</CardGroup>
105> **[Understand the architecture](/docs/2026-07-28/learn/architecture)**
106>
107> Dive deeper into how MCP works and its architecture
124108 
125109Remote MCP servers unlock powerful possibilities for extending Claude's capabilities. As you become familiar with these integrations, you'll discover new ways to streamline your workflows and accomplish complex tasks more efficiently.
126110 
Feedback