Discover Awesome MCP Servers

Extend your agent with 84,516 capabilities via MCP servers.

All84,516
MCP with Langchain Sample Setup

MCP with Langchain Sample Setup

Okay, here's a sample setup for an MCP (Modular Component Protocol) server and client, designed to be compatible with LangChain. This example focuses on a simple "summarization" task, but you can adapt it to other LangChain functionalities. **Important Considerations:** * **MCP (Modular Component Protocol):** MCP isn't a widely standardized protocol. This example uses a simplified, custom implementation based on JSON over HTTP for demonstration purposes. In a real-world scenario, you might consider more robust solutions like gRPC, Thrift, or even well-defined REST APIs. * **LangChain Integration:** The key is to use LangChain components (e.g., LLMs, chains, document loaders) *within* the MCP server to process requests. The client sends data, the server uses LangChain to process it, and the server returns the result. * **Error Handling:** This is a simplified example. Robust error handling (try-except blocks, logging, proper HTTP status codes) is crucial in a production environment. * **Security:** This example lacks security measures (authentication, authorization). Implement appropriate security based on your needs. * **Asynchronous Operations:** For more complex tasks, consider using asynchronous operations (e.g., `asyncio` in Python) to improve performance and prevent blocking. **Python Code (Example):** **1. MCP Server (using Flask):** ```python from flask import Flask, request, jsonify from langchain.llms import OpenAI from langchain.chains.summarize import load_summarize_chain from langchain.document_loaders import TextLoader # Or other loaders from langchain.text_splitter import CharacterTextSplitter import os # Set your OpenAI API key (or use environment variables) os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY" # Replace with your actual key app = Flask(__name__) @app.route('/summarize', methods=['POST']) def summarize_text(): try: data = request.get_json() text = data.get('text') if not text: return jsonify({'error': 'Missing "text" parameter'}), 400 # LangChain components llm = OpenAI(temperature=0) # Adjust temperature as needed summarize_chain = load_summarize_chain(llm, chain_type="map_reduce") # or "stuff", "refine" # Prepare the document (using a dummy TextLoader for demonstration) # In a real scenario, you might load from a file, database, etc. # For large texts, split into chunks text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_text(text) # Create LangChain documents from the text chunks from langchain.docstore.document import Document docs = [Document(page_content=t) for t in texts] # Run the summarization chain summary = summarize_chain.run(docs) return jsonify({'summary': summary}) except Exception as e: print(f"Error: {e}") # Log the error return jsonify({'error': str(e)}), 500 # Return error with status code if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5000) # Make accessible on network ``` **2. MCP Client (using `requests`):** ```python import requests import json def summarize_with_mcp(text, server_url="http://localhost:5000/summarize"): """ Sends text to the MCP server for summarization. Args: text: The text to summarize. server_url: The URL of the MCP server's summarize endpoint. Returns: The summary from the server, or None if there was an error. """ try: payload = {'text': text} headers = {'Content-Type': 'application/json'} response = requests.post(server_url, data=json.dumps(payload), headers=headers) response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx) data = response.json() return data.get('summary') except requests.exceptions.RequestException as e: print(f"Error connecting to server: {e}") return None except json.JSONDecodeError as e: print(f"Error decoding JSON response: {e}") return None except Exception as e: print(f"An unexpected error occurred: {e}") return None if __name__ == '__main__': sample_text = """ This is a long piece of text that needs to be summarized. It contains important information about LangChain and MCP. LangChain is a powerful framework for building applications using large language models. MCP, in this context, is a simple protocol for communication between a client and a server. The server uses LangChain to process requests from the client. This example demonstrates a basic summarization task. More complex tasks can be implemented using different LangChain components and chains. Error handling and security are important considerations for production deployments. """ summary = summarize_with_mcp(sample_text) if summary: print("Summary:", summary) else: print("Failed to get summary.") ``` **Explanation:** * **Server (Flask):** * Uses Flask to create a simple HTTP server. * The `/summarize` endpoint receives POST requests with a JSON payload containing the `text` to summarize. * It initializes LangChain components: `OpenAI` (the LLM) and `load_summarize_chain` (the summarization chain). You'll need an OpenAI API key. * It loads the text into a LangChain `Document`. For larger texts, it splits the text into chunks using `CharacterTextSplitter`. * It runs the summarization chain and returns the summary in a JSON response. * Includes basic error handling. * **Client:** * Uses the `requests` library to send a POST request to the server's `/summarize` endpoint. * It packages the text to be summarized in a JSON payload. * It handles potential errors during the request (e.g., connection errors, bad responses). * It prints the summary received from the server. **How to Run:** 1. **Install Dependencies:** ```bash pip install flask langchain openai requests tiktoken ``` 2. **Set OpenAI API Key:** Replace `"YOUR_OPENAI_API_KEY"` in the server code with your actual OpenAI API key. Consider using environment variables for security. 3. **Run the Server:** ```bash python your_server_file.py # e.g., python mcp_server.py ``` 4. **Run the Client:** ```bash python your_client_file.py # e.g., python mcp_client.py ``` **Key Adaptations for Different LangChain Tasks:** * **Different Chains:** Instead of `load_summarize_chain`, use other LangChain chains (e.g., `LLMChain`, `ConversationalRetrievalChain`) based on the task you want to perform. * **Different LLMs:** Use other LLMs besides `OpenAI` (e.g., `HuggingFaceHub`, `Cohere`). You'll need to install the appropriate LangChain integration and configure the LLM. * **Data Loading:** Use different LangChain document loaders (e.g., `WebBaseLoader`, `CSVLoader`, `PDFMinerLoader`) to load data from various sources. * **Input/Output:** Adjust the input and output data formats in the server and client to match the requirements of your task. For example, you might send a question and receive an answer, or send a list of documents and receive a ranked list of relevant documents. * **Prompt Engineering:** Carefully design the prompts used in your LangChain chains to achieve the desired results. **Example in Portuguese (Translation of the Explanation):** Aqui está uma configuração de exemplo para um servidor e cliente MCP (Modular Component Protocol), projetada para ser compatível com LangChain. Este exemplo se concentra em uma tarefa simples de "resumo", mas você pode adaptá-lo para outras funcionalidades do LangChain. **Considerações Importantes:** * **MCP (Modular Component Protocol):** MCP não é um protocolo amplamente padronizado. Este exemplo usa uma implementação personalizada simplificada baseada em JSON sobre HTTP para fins de demonstração. Em um cenário do mundo real, você pode considerar soluções mais robustas como gRPC, Thrift ou até mesmo APIs REST bem definidas. * **Integração com LangChain:** A chave é usar componentes LangChain (por exemplo, LLMs, chains, carregadores de documentos) *dentro* do servidor MCP para processar solicitações. O cliente envia dados, o servidor usa LangChain para processá-los e o servidor retorna o resultado. * **Tratamento de Erros:** Este é um exemplo simplificado. O tratamento robusto de erros (blocos try-except, registro, códigos de status HTTP adequados) é crucial em um ambiente de produção. * **Segurança:** Este exemplo carece de medidas de segurança (autenticação, autorização). Implemente a segurança apropriada com base em suas necessidades. * **Operações Assíncronas:** Para tarefas mais complexas, considere usar operações assíncronas (por exemplo, `asyncio` em Python) para melhorar o desempenho e evitar bloqueios. **Código Python (Exemplo):** (O código Python permaneceria o mesmo, pois é código e não precisa ser traduzido. Apenas a explicação é traduzida.) **Explicação:** * **Servidor (Flask):** * Usa Flask para criar um servidor HTTP simples. * O endpoint `/summarize` recebe solicitações POST com um payload JSON contendo o `text` a ser resumido. * Ele inicializa os componentes LangChain: `OpenAI` (o LLM) e `load_summarize_chain` (a chain de resumo). Você precisará de uma chave de API OpenAI. * Ele carrega o texto em um `Document` LangChain. Para textos maiores, ele divide o texto em partes usando `CharacterTextSplitter`. * Ele executa a chain de resumo e retorna o resumo em uma resposta JSON. * Inclui tratamento de erros básico. * **Cliente:** * Usa a biblioteca `requests` para enviar uma solicitação POST para o endpoint `/summarize` do servidor. * Ele empacota o texto a ser resumido em um payload JSON. * Ele lida com possíveis erros durante a solicitação (por exemplo, erros de conexão, respostas ruins). * Ele imprime o resumo recebido do servidor. **Como Executar:** (As instruções de execução permanecem as mesmas, pois são comandos e não precisam ser traduzidas.) **Principais Adaptações para Diferentes Tarefas LangChain:** * **Chains Diferentes:** Em vez de `load_summarize_chain`, use outras chains LangChain (por exemplo, `LLMChain`, `ConversationalRetrievalChain`) com base na tarefa que você deseja executar. * **LLMs Diferentes:** Use outros LLMs além de `OpenAI` (por exemplo, `HuggingFaceHub`, `Cohere`). Você precisará instalar a integração LangChain apropriada e configurar o LLM. * **Carregamento de Dados:** Use diferentes carregadores de documentos LangChain (por exemplo, `WebBaseLoader`, `CSVLoader`, `PDFMinerLoader`) para carregar dados de várias fontes. * **Entrada/Saída:** Ajuste os formatos de dados de entrada e saída no servidor e no cliente para corresponder aos requisitos de sua tarefa. Por exemplo, você pode enviar uma pergunta e receber uma resposta, ou enviar uma lista de documentos e receber uma lista classificada de documentos relevantes. * **Engenharia de Prompt:** Projete cuidadosamente os prompts usados em suas chains LangChain para obter os resultados desejados. This provides a basic framework. Remember to adapt it to your specific use case and add proper error handling, security, and performance optimizations. Good luck!

steps-mcp

steps-mcp

Task planning and execution MCP server with durable SQLite storage and a browser UI for reviewing plans and following progress.

Resend MCP Server

Resend MCP Server

Enables sending emails via the Resend API from Claude, with tools for sending, checking delivery status, listing recent emails, and managing domains.

GraphMemory-IDE

GraphMemory-IDE

An AI-assisted, long-term memory system for IDEs, powered by Kuzu graph database. GraphMemory-IDE is an MCP server that provides semantic vector search, graph-based knowledge storage, and real-time analytics.

Mirdan

Mirdan

Automatically enhances developer prompts with quality requirements, codebase context, and architectural patterns, then orchestrates other MCP servers to ensure AI coding assistants produce high-quality, structured code that follows best practices and security standards.

TickTick MCP

TickTick MCP

A remote MCP server that enables Claude to create and manage TickTick to-dos using the TickTick Open API. It supports nine tools for projects, tasks, and sections, and works across all Claude platforms (web, mobile, desktop, Cowork).

phren

phren

A persistent memory server for AI agents that stores findings, tasks, and patterns in Markdown files within a git repository, enabling context injection across multiple AI tools.

Weather Israel MCP

Weather Israel MCP

Enables fetching weather forecasts for Israeli cities via browser automation with Playwright, no API needed.

Interactive Feedback MCP

Interactive Feedback MCP

Enables AI assistants to request user feedback and confirmation to prevent speculative tool calls and reduce resource usage. It streamlines task completion by consolidating multiple potential steps into a single, feedback-aware process.

Expense_Tracker_MCP

Expense_Tracker_MCP

An AI-powered expense management server that enables adding, searching, and analyzing expenses using natural language through the Model Context Protocol.

Anonymix MCP

Anonymix MCP

Provides local anonymization of Czech legal documents by replacing sensitive entities with pseudonyms to ensure privacy during LLM interactions. It allows users to safely process documents like contracts and judgments by keeping original data offline and facilitating local deanonymization.

flashcard-mcp

flashcard-mcp

A lightweight MCP server that adds spaced-repetition flashcards (SM-2) to AI assistants, storing data locally in SQLite and enabling card creation, review, and scheduling.

Whoop MCP Server

Whoop MCP Server

Exposes Whoop fitness data (recovery, sleep, strain, workouts) to Claude for use as a daily training coach, enabling natural language queries about your health metrics and training readiness.

kef-mcp

kef-mcp

MCP server for controlling KEF wireless speakers (LSX II, LS50 Wireless II, LS60) and playing Spotify on them via local network and Spotify Web API.

Copper CRM MCP Server

Copper CRM MCP Server

Enables AI agents to read and manage Copper CRM data, including searching people, companies, and opportunities, listing pipelines, and logging activities or creating tasks.

Continuo Memory System

Continuo Memory System

Enables persistent memory and semantic search for development workflows with hierarchical compression. Store and retrieve development knowledge across IDE sessions using natural language queries, circumventing context window limitations.

framefetch

framefetch

Agent-first video-data API + MCP across 6 platforms (YouTube/Shorts, TikTok, Reddit, Instagram, Pinterest): metadata, insights, Whisper transcript, and parametric frames. Pay-per-call via x402 (USDC) or Stripe.

Brickognize MCP Server

Brickognize MCP Server

Identifies LEGO parts, sets, and minifigures from local image files using the Brickognize API. It provides specialized tools for specific item recognition and integrates LEGO identification capabilities into MCP-enabled environments.

tokencast

tokencast

Pre-execution cost estimation for LLM agent workflows, providing cost estimates before running tasks and improving accuracy over time through calibration.

gemini-image-mcp

gemini-image-mcp

Enables Claude Code to generate and edit images using Google's Gemini and Imagen models on Vertex AI, with support for multiple models, aspect ratios, and image fusion.

linux-computer-use

linux-computer-use

MCP server enabling AI agents to control a real Linux browser with live view, human takeover, and safety guardrails.

playwright-mcp-server

playwright-mcp-server

Deploys a stateless remote MCP server on Cloudflare Workers without authentication, enabling tools to be used with Cloudflare AI Playground or local clients like Claude Desktop.

oaid-mcp

oaid-mcp

Enables AI agents to securely use Open Agent ID credentials for signing requests, looking up agent data, and exchanging encrypted messages. It performs all cryptographic operations within the server process to ensure private keys are never exposed to the AI agent.

SEOforGPT MCP Server

SEOforGPT MCP Server

Enables AI-driven brand visibility monitoring and SEO project management via the SEOforGPT API. Users can execute brand visibility checks, list projects, and retrieve detailed visibility reports through natural language interactions.

Hono MCP Sample Server

Hono MCP Sample Server

A sample Model Context Protocol server built with Hono framework that provides weather and news resources, calculator and string reversal tools, and code review prompt templates.

MCP Aseps

MCP Aseps

A modular MCP server suite that provides core tools, long-term memory, knowledge RAG, skills registry, and external integrations for AI agents.

wheelfor-mcp

wheelfor-mcp

Create, spin, and manage shareable decision wheels on wheelfor.com. Supports creating wheels from any list of options, spinning for a random result, and getting a permanent shareable URL — no account required.

rce-cho-mcp

rce-cho-mcp

Enables querying the Dutch RCE Cultural Heritage Objects linked data endpoint via SPARQL, with ontology guidance and query validation for safe, accurate results.

Lightbringer

Lightbringer

Enables patent management workflows inside AI tools, allowing users to capture and refine inventions, collaborate with attorneys, and access portfolio context through natural language.

Slack Lists MCP Server

Slack Lists MCP Server

Enables AI assistants to interact with Slack Lists through comprehensive tools for creating, retrieving, filtering, and managing list items. Supports bulk operations, data export, subtask creation, and all Slack List field types with robust error handling and production-ready implementation.