Skip to content

[mcp-adapters] Request headers are still not being set for Legacy SSE transport #8194

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
gauravmindzk opened this issue May 9, 2025 · 7 comments · Fixed by #8239
Closed

Comments

@gauravmindzk
Copy link

gauravmindzk commented May 9, 2025

my app’s backend is written in nodejs and I want to develop a chatbot in my application powered by Pinecone Assistant’s MCP server.
I’ve found the javascript code for uploading data to the Pinecone Assistant ( Upload files - Pinecone Docs )

I want a similar code for ( Use an Assistant MCP server - Pinecone Docs ) this .
Below is my agent’s code using Python:

from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI
import asyncio
from langgraph.checkpoint.mongodb.aio import AsyncMongoDBSaver

mcp_endpoint = f"pinecone-mcp-endpoint"
MONGODB_URI = "mongo-db-uri"

async def main():
    model = ChatOpenAI(model="gpt-4o-mini", api_key='openai-api-key')
    
    # Create the MongoDB client and checkpointer inside the async context
    async with AsyncMongoDBSaver.from_conn_string(MONGODB_URI) as checkpointer:
        async with MultiServerMCPClient(
            {
                "pinecone_assistant": {
                    "url": mcp_endpoint,
                    "transport": "sse",
                    "headers": {
                        "Authorization": f"Bearer pinecone-api-key"
                    }
                }
            }
        ) as client:
            agent = create_react_agent(model, client.get_tools(), checkpointer=checkpointer)
            config = {"configurable": {"thread_id": "1"}}
            response = await agent.ainvoke({"messages": "hello"}, config)
            print(response["messages"][-1].content)

# Run the async function
if __name__ == "__main__":
    asyncio.run(main())

I want its equivalent in javascript .

I came across Langchain’s github repo GitHub - langchain-ai/langchainjs-mcp-adapters: Adapters for integrating Model Context Protocol (MCP) tools with LangChain.js applications, supporting both stdio and SSE transports.
and tried setting up the code .

import { MultiServerMCPClient } from "@langchain/mcp-adapters";
import { ChatOpenAI } from "@langchain/openai";
import { createReactAgent } from "@langchain/langgraph/prebuilt";

// Create client and connect to server
const client = new MultiServerMCPClient({
  // Global tool configuration options
  // Whether to throw on errors if a tool fails to load (optional, default: true)
  throwOnLoadError: true,
  // Whether to prefix tool names with the server name (optional, default: true)
  prefixToolNameWithServerName: true,
  // Optional additional prefix for tool names (optional, default: "mcp")
  additionalToolNamePrefix: "mcp",
  // Server configuration
  mcpServers: {
    pinecone_assistant: {
      url: "pinecone-mcp-server-url",
      transport: "sse",
      headers: {
        Authorization:
          "Bearer pinecone-api-key",
      },
      useNodeEventSource: true,
      reconnect: {
        enabled: true,
        maxAttempts: 5,
        delayMs: 2000,
      },
    },
  },
});

const tools = await client.getTools();

// Create an OpenAI model
const model = new ChatOpenAI({
  modelName: "gpt-4o-mini",
  temperature: 0,
  apiKey:"openai-api-key"
});

// Create the React agent
const agent = createReactAgent({
  llm: model,
  tools,
});

// Run the agent
try {
  const aiResponse = await agent.invoke({
    messages: [{ role: "user", content: "hello" }],
  });
  console.log(aiResponse);
} catch (error) {
  console.error("Error during agent execution:", error);
  // Tools throw ToolException for tool-specific errors
  if (error.name === "ToolException") {
    console.error("Tool execution failed:", error.message);
  }
}

await client.close();

I'm getting an error when running this agent.

PS C:\Users\gaura\Desktop\Chatbot> node agent.js
(node:22864) [DEP0040] DeprecationWarning: The punycode module is deprecated. Please use a userland alternative instead.
(Use node --trace-deprecation … to show where the warning was created)
file:///C:/Users/gaura/Desktop/Chatbot/node_modules/@langchain/mcp-adapters/dist/client.js:434
throw new MCPClientError(Failed to create SSE transport for server “${serverName}”: ${error}, serverName);
^
MCPClientError: Failed to create SSE transport for server “pinecone_assistant”: MCPClientError: Failed to connect to SSE server “pinecone_assistant”: Error: SSE error: Non-200 status code (401)
at MultiServerMCPClient._initializeSSEConnection (file:///C:/Users/gaura/Desktop/Chatbot/node_modules/@langchain/mcp-adapters/dist/client.js:434:19)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async MultiServerMCPClient.initializeConnections (file:///C:/Users/gaura/Desktop/Chatbot/node_modules/@langchain/mcp-adapters/dist/client.js:297:17)
at async MultiServerMCPClient.getTools (file:///C:/Users/gaura/Desktop/Chatbot/node_modules/@langchain/mcp-adapters/dist/client.js:314:9)
at async file:///C:/Users/gaura/Desktop/Chatbot/agent.js:33:15 {
serverName: ‘pinecone_assistant’
}
Node.js v22.11.0

Package Versions:

    "@langchain/mcp-adapters": "^0.4.2",
    "@langchain/openai": "^0.5.10",
    "@langchain/langgraph": "^0.2.68",
@benjamincburns
Copy link
Collaborator

@gauravmindzk I think this may have been fixed in v0.4.3, but can you please test with @langchain/[email protected] (releasing now) and report back? I'm not sure if pincone supports streamable HTTP yet, but if it does, please try with that (likely requires removing the transport: "sse" line from your config, and changing the url path to /mcp instead of /sse). It Streamable HTTP has built-in support for passing headers, whereas it had to be sort of hacked in for SSE.

I'll leave this open for now, but please report back what you find and close if things are working for you. Thanks!

@benjamincburns benjamincburns changed the title Not able to connect to Pinecone MCP [mcp-adapters] Not able to connect to Pinecone MCP May 16, 2025
@benjamincburns
Copy link
Collaborator

Migrating issues over to langchainjs monorepo, as we've moved this project over there.

@benjamincburns benjamincburns transferred this issue from langchain-ai/langchainjs-mcp-adapters May 16, 2025
@gauravmindzk
Copy link
Author

hi @benjamincburns , will try again and let you know, thanks for the fix

@botkevin
Copy link

Not sure if relevant, but I am doing a similar thing, and for example, with code like

for (const [key, value] of Object.entries(mcpConnectionConfig.servers)) {
    const connection: SSEConnection = {
      transport: "sse" as const,
      url: value.url,
      headers: {
        "Authorization": `Bearer test123`,
      },
    };
    sseConnections[key] = connection;
  }

  const clientConfig: ClientConfig = {
    mcpServers: sseConnections,
  };
  const mcpClient = new MultiServerMCPClient(clientConfig);
  await mcpClient.initializeConnections();

Still seeing that the Authorization header is missing in the request with v0.4.5

@benjamincburns
Copy link
Collaborator

@botkevin what happens if you drop the transport: "sse" as const line?

@botkevin
Copy link

botkevin commented May 21, 2025

@benjamincburns Still doesn't work. I first get
POST /sse 405 Method Not Allowed
Which does have the Authorization header, then it falls back to
GET /sse 401
Because it doesn't have the Auth header

@botkevin
Copy link

Pretty sure this is the same issue as langchain-ai/langchainjs-mcp-adapters#65 (comment), I believe that SSE header support was just never supported in lieu of Streamable HTTP

@benjamincburns benjamincburns changed the title [mcp-adapters] Not able to connect to Pinecone MCP [mcp-adapters] Request headers are still not being set for Legacy SSE transport May 22, 2025
benjamincburns added a commit that referenced this issue May 23, 2025
BREAKING_CHANGE: Drops the `useNodeEventSource` flag and stops passing
an empty eventSourceInit object to Streamable HTTP and SSE transport
constructors. If there continues to be header passing issues as a result
of the way `SSEClientTransport` and `StreamableHTTPClientTransport`
handle EventSource initialization, the correct fix will be to PR a
change to the MCP SDK that changes how headers are populated on
EventSource initialization.

fixes #8196
fixes #8194
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants