Logo de Mcp

Mcp

Organização
managedcode
mcp

Build or consume Model Context Protocol (MCP) servers and clients in .NET using the official MCP C# SDK, including stdio, Streamable HTTP, tools, prompts, resources, and capability negotiation. USE FOR: .NET MCP servers or clients; stdio versus HTTP transport choices; tools, resources, prompts, completions, and capability negotiation. DO NOT USE FOR: unrelated stacks; generic tasks that do not need this specific guidance. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made.

Visão geral

Publicado pormanagedcode
Repositóriodotnet-skills
Nome da habilidademcp
Estrelas
492
Forks
38
Arquivos incluídos
3
LicençaMIT
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    Habilidades de IA são Markdown simples, não código específico de um provedor, por isso funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • 3 arquivos incluídos

    Scripts, modelos de documentos e referências que o modelo pode ler enquanto trabalha. Os arquivos são somente leitura e nunca são executados.

  • Código aberto

    Publicada por managedcode no GitHub. Leia o conteúdo-fonte antes de instalar.

Instalação

Instale a habilidade de IA Mcp no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL da pasta da habilidade exibida abaixo e confirme.
    https://github.com/managedcode/dotnet-skills/tree/main/catalog/Libraries/MCP/skills/mcp
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Nova habilidade → Via URL GitHub, depois cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/managedcode/dotnet-skills.git /tmp/dotnet-skills
mkdir -p .claude/skills
cp -r /tmp/dotnet-skills/catalog/Libraries/MCP/skills/mcp .claude/skills/mcp
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Mcp em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Mcp automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Mcp não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

MCP C# SDK for .NET

Trigger On

  • building or consuming MCP servers from a .NET application or library
  • choosing between stdio and HTTP transport for MCP
  • exposing tools, resources, prompts, completions, or logging to an MCP host
  • connecting a .NET app to an existing MCP server and passing discovered tools into IChatClient
  • bootstrapping a minimal MCP client/server from the .NET AI quickstarts or publishing a server to the MCP Registry
  • implementing capability-aware flows such as roots, sampling, elicitation, subscriptions, session resumption, or enterprise managed authorization

Use This Skill Instead Of

  • Use mcp when protocol interoperability is the requirement.
  • Use microsoft-extensions-ai when you only need model/provider abstraction or local tool orchestration without the MCP wire protocol.
  • Use microsoft-agent-framework when the main problem is agent orchestration; combine it with mcp only when those agents must consume or expose MCP endpoints.
  • Use the .NET AI quickstarts for the very first vertical slice, then come back here to harden transport, capability negotiation, publishing, and host interoperability.

Documentation

References

Load only what the task needs:

  • references/patterns.md - current server/client patterns, transports, capabilities, filters, and chat-client integration
  • references/security.md - safe error handling, auth boundaries, stdio logging hygiene, and defensive tool/resource patterns

Package Selection

PackageChoose when
ModelContextProtocol.CoreYou only need a client or low-level server APIs and want the smallest dependency set.
ModelContextProtocolYou want the main SDK package with hosting, DI, attribute discovery, and stdio server support. Start here for most projects.
ModelContextProtocol.AspNetCoreYou are hosting a remote MCP server in ASP.NET Core over HTTP. This includes the main package.

Transport Selection

TransportUse whenNotes
StdioClientTransport / WithStdioServerTransport()The MCP server should run as a local child process.Best for local tooling and editor/agent integrations.
HttpClientTransport + HttpTransportMode.StreamableHttpThe server is remote or should be reachable over HTTP.Recommended HTTP transport; supports streaming and session resumption.
HttpTransportMode.SseYou must connect to an older SSE-only server.Legacy compatibility only; do not choose this for new servers.

Current v2.2 Notes

  • The August 2026 .NET AI MCP documentation separates a getting-started hub, client and server quickstarts, MCP Registry publishing, and a server-resource index. Use those pages to bootstrap a vertical slice, then return to the C# SDK docs here for exact transport, capability, authorization, and lifecycle behavior.
  • SDK v2.0.0 aligns with MCP 2026-07-28: HTTP is stateless by default, clients negotiate with server/discover before falling back to legacy initialize, Tasks move to ModelContextProtocol.Extensions.Tasks, and Roots, Sampling, and Logging are deprecated for the new protocol. Set HttpServerTransportOptions.Stateless = false only for an intentional stateful compatibility requirement.
  • SDK v2.1.0 adds an opt-in subscriptions/listen server handler, keeps AutoDetect usable after a provisional SSE failure, preserves HTTP status codes across target frameworks, and falls back to initialize when server/discover fails at the HTTP layer. Add custom notification streams only when both peers negotiate the extension.
  • SDK v2.2.0 adds HttpServerSessionMode so one ASP.NET Core endpoint can serve stateful and stateless clients across the MCP 2025-11-25 and 2026-07-28 protocol versions. Choose the mode explicitly, test both negotiated paths when compatibility matters, and upgrade before working around malformed percent-encoded request headers because the release fixes that decoding failure.
  • Before moving from v1.4.x, update structured-result consumers to accept non-object values directly, require Tool.inputSchema in custom payloads, move Tasks to the extension package, and test PKCE S256 plus issuer validation in OAuth metadata.
  • Enterprise managed authorization now has an SDK surface through IdentityAssertionGrantProvider for the Identity Assertion Authorization Grant flow. Use it only when the enterprise SSO and MCP authorization-server contract is part of the actual scenario.
  • StdioClientTransportOptions.InheritEnvironmentVariables controls whether child-process MCP servers inherit the parent environment. Set it intentionally when launching untrusted or third-party servers.
  • Streamable HTTP session DELETE is hardened to require the same authenticated user that opened the session. Do not build custom session cleanup paths that bypass that authorization check.
  • Stdio transport no longer logs child-process environment variables at trace level, but server authors should still treat environment variables as secrets.

Workflow

  1. Pick the package and transport first.

    • Local child-process server: ModelContextProtocol + WithStdioServerTransport().
    • Remote server: ModelContextProtocol.AspNetCore + WithHttpTransport() + MapMcp().
    • Client-only app: start with ModelContextProtocol or ModelContextProtocol.Core.
    • Registry distribution: pair a minimal server with the MCP Registry publishing flow only after the server contract is stable.
  2. Model the MCP surface explicitly.

    • Tools: [McpServerToolType] + [McpServerTool]
    • Resources: [McpServerResourceType] + [McpServerResource]
    • Prompts: [McpServerPromptType] + [McpServerPrompt]
    • Use custom handlers or filters only for cross-cutting behavior, protocol extensions, or advanced routing.
  3. Prefer attribute discovery for straightforward servers.

csharp
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
using System.ComponentModel;

var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(options =>
{
    options.LogToStandardErrorThreshold = LogLevel.Trace;
});

builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithToolsFromAssembly();

await builder.Build().RunAsync();

[McpServerToolType]
public static class EchoTool
{
    [McpServerTool, Description("Echoes the message back to the client.")]
    public static string Echo(string message) => $"hello {message}";
}
  1. For HTTP servers, use the ASP.NET Core transport and map the endpoint directly.
csharp
using ModelContextProtocol.Server;
using System.ComponentModel;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddMcpServer()
    .WithHttpTransport()
    .WithToolsFromAssembly();

var app = builder.Build();
app.MapMcp("/mcp");
app.Run();

[McpServerToolType]
public static class EchoTool
{
    [McpServerTool, Description("Echoes the message back to the client.")]
    public static string Echo(string message) => $"hello {message}";
}
  1. When consuming a server, use McpClient.CreateAsync(...) and stay capability-aware.
csharp
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;

var transport = new StdioClientTransport(new StdioClientTransportOptions
{
    Name = "Everything",
    Command = "npx",
    Arguments = ["-y", "@modelcontextprotocol/server-everything"],
});

await using var client = await McpClient.CreateAsync(transport);

IList<McpClientTool> tools = await client.ListToolsAsync();

if (client.ServerCapabilities.Prompts is not null)
{
    var prompts = await client.ListPromptsAsync();
}
  1. Treat optional features as negotiated capabilities, not assumptions.

    • Client capabilities: configure McpClientOptions.Capabilities for roots, sampling, and elicitation.
    • Server capabilities are inferred from registered features.
    • Check client.ServerCapabilities before using completions, logging, prompt list-change notifications, or resource subscriptions.
    • Use client.NegotiatedProtocolVersion or server.NegotiatedProtocolVersion only when version-specific behavior matters.
  2. Keep HTTP guidance current.

    • Streamable HTTP is the recommended transport for remote servers.
    • MapMcp() also serves SSE compatibility endpoints for older clients.
    • HTTP clients can use AutoDetect by default, or force StreamableHttp / Sse.
    • Session resumption is available for Streamable HTTP through McpClient.ResumeSessionAsync(...).
    • For authenticated Streamable HTTP sessions, cleanup and resume operations must preserve the same user boundary.
  3. Treat the .NET AI MCP quickstarts as bootstrap examples.

    • build-mcp-client and build-mcp-server are good starting points when the surrounding app is still MEAI-centric.
    • publish-mcp-registry is the distribution step, not the design step. Stabilize the protocol surface before publishing.
  4. Respect current error and serialization rules.

    • Tool exceptions normally come back as CallToolResult.IsError == true.
    • Throw McpProtocolException only for protocol-level JSON-RPC failures.
    • McpClientTool inherits from AIFunction, so discovered tools can be passed directly into IChatClient.
    • Experimental APIs use MCPEXP... diagnostics; suppress them intentionally, not globally by accident.
    • If you use a custom JsonSerializerContext, prepend McpJsonUtilities.DefaultOptions.TypeInfoResolver so MCP protocol types keep the SDK's contract.

Anti-Patterns To Avoid

Anti-patternWhy it causes troubleBetter approach
Picking HTTP transport for a purely local child-process scenarioAdds unnecessary hosting, auth, and deployment surfaceUse stdio for local/editor-hosted integrations
Treating SSE as the default remote transportLocks new work to legacy behaviorPrefer Streamable HTTP and keep SSE only for backward compatibility
Writing tools without [Description] metadataHosts and models lose schema clarityDescribe tool purpose and parameters explicitly
Returning huge binary/text payloads from every tool callBloats context and slows hostsReturn focused content and move large data to resources
Logging to stdout on stdio serversCorrupts the protocol streamSend logs to stderr
Assuming prompts/resources/logging/completions existBreaks against partial implementationsCheck negotiated capabilities first
Using filters for normal business logicMakes handlers opaque and hard to reason aboutKeep filters for cross-cutting policy, audit, or protocol plumbing

Deliver

  • a correctly packaged MCP server or client that matches the deployment topology
  • explicit tool/resource/prompt definitions with descriptions and bounded payloads
  • capability-aware handling for optional MCP features
  • validation notes for transport, auth boundary, and host/client interoperability

Validate

  • chosen package matches the topology: Core, ModelContextProtocol, or AspNetCore
  • stdio servers do not write logs or diagnostics to stdout
  • HTTP servers use MapMcp() and are tested at the final route, for example /mcp
  • tools, resources, and prompts use current [McpServer*] attributes or documented handler/filter alternatives
  • client code checks ServerCapabilities before using subscriptions, completions, logging, or prompt/resource list-change flows
  • Streamable HTTP is the default for new remote servers; SSE is used only for legacy compatibility
  • experimental APIs and custom serialization settings are reviewed intentionally rather than copied blindly

Arquivos incluídos

O modelo lê esses arquivos sob demanda enquanto a habilidade está carregada. Eles são disponibilizados para leitura e nunca são executados.

Perguntas frequentes

O que a habilidade de IA Mcp faz?

Build or consume Model Context Protocol (MCP) servers and clients in .NET using the official MCP C# SDK, including stdio, Streamable HTTP, tools, prompts, resources, and capability negotiation. USE FOR: .NET MCP servers or clients; stdio versus HTTP transport choices; tools, resources, prompts, completions, and capability negotiation. DO NOT USE FOR: unrelated stacks; generic tasks that do not need this specific guidance. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made.

Por que usar Mcp no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. Mcp é escrito em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. O TypingMind usa suas próprias chaves de API, então o pagamento é feito diretamente aos provedores, em vez de uma assinatura por licença de usuário, e suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Mcp no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/managedcode/dotnet-skills/tree/main/catalog/Libraries/MCP/skills/mcp. O TypingMind lê o arquivo SKILL.md, reúne os arquivos da habilidade e a instala para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Mcp?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Mcp?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Mcp com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Mcp é gratuita?

Sim. A habilidade é publicada no GitHub por managedcode sob a licença MIT. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, modelos de documento ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas para chamar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA fornece conhecimento e um processo ao modelo: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver todos

Crie seu próprio espaço de IA agora

Inscreva-se na nossa newsletter para receber novidades sobre recursos e futuros sorteios 👇