You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

@socketsecurity/mcp

Package Overview
Dependencies
Maintainers
2
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@socketsecurity/mcp - npm Package Compare versions

Comparing version

to
0.0.8

163

build/index.js

@@ -217,6 +217,31 @@ #!/usr/bin/env node

const httpServer = createServer(async (req, res) => {
// Enable CORS
res.setHeader('Access-Control-Allow-Origin', '*');
// Validate Origin header as required by MCP spec
const origin = req.headers.origin;
const allowedOrigins = [
'http://localhost:3000',
'http://127.0.0.1:3000',
'https://mcp.socket.dev',
'https://mcp.socket-staging.dev'
];
const isValidOrigin = !origin || allowedOrigins.includes(origin);
if (origin && !isValidOrigin) {
logger.warn(`Rejected request from invalid origin: ${origin}`);
res.writeHead(403, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
jsonrpc: '2.0',
error: { code: -32000, message: 'Forbidden: Invalid origin' },
id: null
}));
return;
}
// Set CORS headers for valid origins
if (origin && isValidOrigin) {
res.setHeader('Access-Control-Allow-Origin', origin);
}
else {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
}
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, mcp-session-id');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, mcp-session-id, Accept, Last-Event-ID');
res.setHeader('Access-Control-Expose-Headers', 'mcp-session-id');
if (req.method === 'OPTIONS') {

@@ -241,2 +266,14 @@ res.writeHead(200);

if (req.method === 'POST') {
// Validate Accept header as required by MCP spec
const acceptHeader = req.headers.accept;
if (!acceptHeader || (!acceptHeader.includes('application/json') && !acceptHeader.includes('text/event-stream'))) {
logger.warn(`Invalid Accept header: ${acceptHeader}`);
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
jsonrpc: '2.0',
error: { code: -32000, message: 'Bad Request: Accept header must include application/json or text/event-stream' },
id: null
}));
return;
}
// Handle JSON-RPC messages

@@ -249,2 +286,13 @@ let body = '';

const sessionId = req.headers['mcp-session-id'];
// Validate session ID format if provided (must contain only visible ASCII characters)
if (sessionId && !/^[\x21-\x7E]+$/.test(sessionId)) {
logger.warn(`Invalid session ID format: ${sessionId}`);
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
jsonrpc: '2.0',
error: { code: -32000, message: 'Bad Request: Session ID must contain only visible ASCII characters' },
id: jsonData.id || null
}));
return;
}
let transport;

@@ -255,9 +303,19 @@ if (sessionId && transports[sessionId]) {

}
else if (!sessionId && isInitializeRequest(jsonData)) {
// New initialization request
else if (!sessionId) {
// Create new session (either for initialize request or fallback)
const newSessionId = randomUUID();
const isInit = isInitializeRequest(jsonData);
if (isInit) {
logger.info(`Creating new session for initialize request: ${newSessionId}`);
}
else {
logger.warn(`Creating fallback session for non-initialize request: ${newSessionId}`);
}
transport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
sessionIdGenerator: () => newSessionId,
onsessioninitialized: (id) => {
transports[id] = transport;
logger.info(`Session initialized: ${id}`);
// Set session ID in response headers as required by MCP spec
res.setHeader('mcp-session-id', id);
}

@@ -277,8 +335,12 @@ });

else {
// Invalid request
// Invalid request - session ID provided but not found
logger.error(`Invalid session ID: ${sessionId}. Active sessions count: ${Object.keys(transports).length}`);
res.writeHead(400);
res.end(JSON.stringify({
jsonrpc: '2.0',
error: { code: -32000, message: 'Bad Request: No valid session ID' },
id: null
error: {
code: -32000,
message: `Bad Request: Invalid session ID. Please initialize a new session first.`
},
id: jsonData.id || null
}));

@@ -304,11 +366,88 @@ return;

else if (req.method === 'GET') {
// Validate Accept header for SSE as required by MCP spec
const acceptHeader = req.headers.accept;
if (!acceptHeader || !acceptHeader.includes('text/event-stream')) {
logger.warn(`GET request without text/event-stream Accept header: ${acceptHeader}`);
res.writeHead(405, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
jsonrpc: '2.0',
error: { code: -32000, message: 'Method Not Allowed: GET requires Accept: text/event-stream' },
id: null
}));
return;
}
// Handle SSE streams
const sessionId = req.headers['mcp-session-id'];
// Validate session ID format
if (sessionId && !/^[\x21-\x7E]+$/.test(sessionId)) {
logger.warn(`Invalid session ID format in GET request: ${sessionId}`);
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
jsonrpc: '2.0',
error: { code: -32000, message: 'Bad Request: Session ID must contain only visible ASCII characters' },
id: null
}));
return;
}
if (!sessionId || !transports[sessionId]) {
res.writeHead(400);
res.end('Invalid or missing session ID');
logger.warn(`SSE request with invalid session ID: ${sessionId}`);
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
jsonrpc: '2.0',
error: { code: -32000, message: 'Bad Request: Invalid or missing session ID for SSE stream' },
id: null
}));
return;
}
// Check for Last-Event-ID header for resumability (optional MCP feature)
const lastEventId = req.headers['last-event-id'];
if (lastEventId) {
logger.info(`SSE resumability requested with Last-Event-ID: ${lastEventId}`);
// Note: Actual resumability implementation would require message storage
// For now, we log the request but don't implement full resumability
}
logger.info(`Opening SSE stream for session: ${sessionId}`);
// Prevent connection timeout and keep it alive
req.socket?.setTimeout(0);
req.socket?.setKeepAlive(true, 30000);
let streamClosed = false;
// Handle client disconnection gracefully
req.on('close', () => {
streamClosed = true;
logger.info(`Client disconnected SSE stream for session: ${sessionId}`);
});
req.on('aborted', () => {
streamClosed = true;
logger.info(`Client aborted SSE stream for session: ${sessionId}`);
});
// Let the MCP transport handle the SSE stream completely
const transport = transports[sessionId];
await transport.handleRequest(req, res);
try {
await transport.handleRequest(req, res);
// If the transport completes without the client disconnecting,
// it might have closed the stream prematurely. Keep it open with heartbeat.
if (!streamClosed && !res.destroyed) {
logger.info(`Transport completed, maintaining SSE stream for session: ${sessionId}`);
// Send periodic heartbeat to keep connection alive
const heartbeat = setInterval(() => {
if (streamClosed || res.destroyed) {
clearInterval(heartbeat);
return;
}
try {
res.write(': heartbeat\n\n');
}
catch (error) {
logger.error(`Heartbeat error for session ${sessionId}:`, error);
clearInterval(heartbeat);
}
}, 30000);
// Clean up heartbeat when connection closes
req.on('close', () => clearInterval(heartbeat));
res.on('close', () => clearInterval(heartbeat));
}
}
catch (error) {
logger.error(`SSE transport error for session ${sessionId}:`, error);
}
}

@@ -315,0 +454,0 @@ else if (req.method === 'DELETE') {

2

package.json
{
"name": "@socketsecurity/mcp",
"version": "0.0.7",
"version": "0.0.8",
"type": "module",

@@ -5,0 +5,0 @@ "main": "./build/index.js",

# Socket MCP Server
[![npm version](https://badge.fury.io/js/@socketsecurity%2Fmcp.svg)](https://badge.fury.io/js/@socketsecurity%2Fmcp)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Socket Badge](https://socket.dev/api/badge/npm/package/@socketsecurity/mcp)](https://socket.dev/npm/package/@socketsecurity/mcp)
A Model Context Protocol (MCP) server for Socket integration, allowing AI assistants to efficiently check dependency vulnerability scores and security information.
🛠️ This project is in early development and rapidly evolving.
## ✨ Features
## Tools
- 🔍 **Dependency Security Scanning** - Get comprehensive security scores for npm, PyPI, and other package ecosystems
- 🌐 **Public Hosted Service** - Use our public server at `https://mcp.socket.dev/` with no setup required
- 🚀 **Multiple Deployment Options** - Run locally via stdio, HTTP, or use our service
- 🤖 **AI Assistant Integration** - Works seamlessly with Claude, VS Code Copilot, Cursor, and other MCP clients
- 📊 **Batch Processing** - Check multiple dependencies in a single request
- 🔒 **No Authentication Required** - Public server requires no API keys or registration
### depscore
🛠️ This project is in early development and rapidly evolving.
The `depscore` tool allows AI assistants to query the Socket API for dependency scoring information. It provides security and quality metrics for packages across different ecosystems.
## 🚀 Quick Start
**Parameters:**
### Option 1: Use the Public Socket MCP Server (Recommended)
- `ecosystem`: The package ecosystem (e.g., npm, PyPI). Defaults to "npm".
- `depname`: The name of the dependency.
- `version`: The version of the dependency. Defaults to "unknown".
The easiest way to get started is to use our public Socket MCP server. **No API key or authentication required!** Click a button below to install the public server in your favorite AI assistant.
## Configuration
### Getting an API key
[![Install in VS Code](https://img.shields.io/badge/VS_Code-Socket_MCP-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect/mcp/install?name=socket-mcp&config={"url":"https://mcp.socket.dev/","type":"http"})
[![Install in Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/install-mcp?name=socket-mcp&config=eyJ0eXBlIjoiaHR0cCIsInVybCI6Imh0dHBzOi8vbWNwLnNvY2tldC5kZXYifQ%3D%3D)
To use the Socket MCP Server, you need to create an API key. You can do this by following [these steps](https://docs.socket.dev/reference/creating-and-managing-api-tokens). The only required permission scope is `packages:list`, which allows the MCP server to query package metadata for dependency scores.
<details><summary><b>Manual Installation Instructions & more MCP Clients</b></summary>
### Usage with Claude Desktop
<details><summary><b>Install in Claude Desktop or Claude Code</b></summary>

@@ -31,28 +38,67 @@ > [!NOTE]

To use this MCP server with Claude Desktop:
To use the public Socket MCP server with Claude Desktop:
1. Install the Socket MCP server:
1. In Claude Desktop, go to Settings > Developer > Edit Config.
```bash
npm install -g @socketsecurity/mcp
```
2. Add the Socket MCP server configuration:
2. Set the API key in your environment:
```json
{
"mcpServers": {
"socket-mcp": {
"type": "http",
"url": "https://mcp.socket.dev/"
}
}
}
```
```bash
export SOCKET_API_KEY=your_api_key_here
```
3. Save the configuration and restart Claude Desktop.
3. In Claude Desktop, go to Settings > Developer > Edit Config.
4. Now you can ask Claude questions like "Check the security score for express version 4.18.2".
The process is similar for Claude Code. See the [Claude Code documentation](https://docs.anthropic.com/en/docs/claude-code/mcp) for more details. Here's an example command to add the Socket MCP server:
```js
```bash
claude mcp add --transport http socket-mcp https://mcp.socket.dev/
```
</details>
<details><summary><b>Install in VS Code</b></summary>
You can install the Socket MCP server using the VS Code CLI:
```bash
# For VS Code with GitHub Copilot
code --add-mcp '{"name":"socket-mcp","type":"http","url":"https://mcp.socket.dev/}'
```
After installation, the Socket MCP server will be available for use with your GitHub Copilot agent in VS Code.
Alternatively, you can manually add it to your VS Code MCP configuration in `.vscode/mcp.json`:
```json
{
"servers": {
"socket-mcp": {
"type": "http",
"url": "https://mcp.socket.dev/"
}
}
}
```
</details>
<details><summary><b>Install in Cursor</b></summary>
Go to `Cursor Settings` -> `MCP` -> `Add new MCP Server`. Name it "socket-mcp", use `http` type with URL `https://mcp.socket.dev/`.
```json
{
"mcpServers": {
"socket-mcp": {
"command": "socket-mcp",
"args": [],
"env": {
"SOCKET_API_KEY": "your-api-key"
}
"type": "http",
"url": "https://mcp.socket.dev/"
}

@@ -63,70 +109,203 @@ }

4. Enter the following:
- Name: Socket
- Command: `socket-mcp`
- Save the configuration.
</details>
5. Now you can ask Claude questions like "Check the security score for express version 4.18.2".
<details><summary><b>Install in Windsurf</b></summary>
The process is similar for Claude Code. See the [Claude Code documentation](https://docs.anthropic.com/en/docs/claude-code/tutorials#set-up-model-context-protocol-mcp) for more details.
> [!WARNING]
> Windsurf does not support `http` type MCP servers yet. Use the `stdio` configuration [below](#option-2a-stdio-mode-default).
### Usage with VS Code
To use the Socket MCP server in Windsurf:
For quick installation, you can use the following link to install the Socket MCP server in VS Code:
1. Open Windsurf Settings
2. Navigate to MCP Servers section
3. Add a new server with the following configuration:
```json
{
"mcpServers": {
"socket-mcp": {
"serverUrl": "https://mcp.socket.dev/mcp"
}
}
}
```
[![Install in VS Code](https://img.shields.io/badge/VS_Code-Socket_MCP-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect/mcp/install?name=socket-mcp&inputs=[{"type":"promptString","id":"socket_api_key","description":"Socket%20API%20key","password":true}]&config={"command":"depscore","type":"stdio","env":{"SOCKET_API_KEY":"${input:socket_api_key}"}})
4. Save the configuration and restart Windsurf if needed.
</details>
To use this MCP server in VS Code:
</details>
1. Set the API key in your environment:
### Option 2: Deploy Socket MCP Server on your machine
If you prefer to run your own instance, you can deploy the Socket MCP server locally using either stdio or HTTP modes.
### Getting an API key
To use a local Socket MCP Server, you need to create an API key. You can do this by following [these steps](https://docs.socket.dev/reference/creating-and-managing-api-tokens). The only required permission scope is `packages:list`, which allows the MCP server to query package metadata for dependency scores.
For local deployment, you have two options:
##### Option 2a: Stdio Mode (Default)
Click a button below to install the self-hosted stdio server in your favorite AI assistant.
[![Install in VS Code](https://img.shields.io/badge/VS_Code-Socket_MCP-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect/mcp/install?name=socket-mcp&config={"command":"npx","args":["@socketsecurity/mcp@latest"],"type":"stdio"})
[![Install in Cursor (stdio)](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/install-mcp?name=socket-mcp-stdio&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyJAc29ja2V0c2VjdXJpdHkvbWNwQGxhdGVzdCJdLCJlbnYiOnsiU09DS0VUX0FQSV9LRVkiOiJ5b3VyLWFwaS1rZXktaGVyZSJ9fQ==)
Claude Code (stdio mode) can be set up with the following command:
```bash
claude mcp add socket-mcp -e SOCKET_API_KEY="your-api-key-here" -- npx -y @socketsecurity/mcp@latest
```
This is how the configuration looks like on most MCP clients:
```json
{
"mcpServers": {
"socket-mcp": {
"command": "npx",
"args": ["@socketsecurity/mcp@latest"],
"env": {
"SOCKET_API_KEY": "your-api-key-here"
}
}
}
}
```
This approach automatically uses the latest version without requiring global installation.
##### Option 2b: HTTP Mode
1. Run the server in HTTP mode using npx:
```bash
export SOCKET_API_KEY=your_api_key_here
MCP_HTTP_MODE=true SOCKET_API_KEY=your-api-key npx @socketsecurity/mcp@latest --http
```
2. In VS Code settings, add the Socket MCP server to your configuration `.vscode/mcp.json` file:
2. Configure your MCP client to connect to the HTTP server:
```json
{
"mcpServers": {
"socket-mcp": {
"type": "http",
"url": "http://localhost:3000"
}
}
}
```
```json
## Tools exposed by the Socket MCP Server
### depscore
The `depscore` tool allows AI assistants to query the Socket API for dependency scoring information. It provides comprehensive security and quality metrics for packages across different ecosystems.
**Parameters:**
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `packages` | Array | ✅ Yes | - | Array of package objects to analyze |
| `packages[].ecosystem` | String | No | `"npm"` | Package ecosystem (`npm`, `pypi`, `cargo`, etc.) |
| `packages[].depname` | String | ✅ Yes | - | Name of the dependency/package |
| `packages[].version` | String | No | `"unknown"` | Version of the dependency |
**Example Usage:**
```json
{
"packages": [
{
"inputs": [
{
"type": "promptString",
"id": "socket_api_key",
"description": "Socket API Key",
"password": true
}
],
"servers": {
"socket-mcp": {
"type": "stdio",
"command": "socket-mcp",
"args": [],
"env": {
"SOCKET_API_KEY": "${input:socket_api_key}"
},
}
}
"ecosystem": "npm",
"depname": "express",
"version": "4.18.2"
},
{
"ecosystem": "pypi",
"depname": "fastapi",
"version": "0.100.0"
}
```
]
}
```
3. Now you can ask questions about dependency security within your VS Code environment.
4. Feel free to add the following to your `.github/copilot-instructions.md` file to control better how the tool is used by your agent:
**Sample Response:**
```
pkg:npm/express@4.18.2: supply_chain: 1.0, quality: 0.9, maintenance: 1.0, vulnerability: 1.0, license: 1.0
pkg:pypi/fastapi@0.100.0: supply_chain: 1.0, quality: 0.95, maintenance: 0.98, vulnerability: 1.0, license: 1.0
```
```markdown
## Socket MCP Server
Always check the dependency scores with the depscore tool when you add a new dependency. If the score is low, consider using an alternative library or writing the code yourself. If you decide to use a library with a low score, make sure to document the reasons for your choice. If you are unsure about the score, ask for a review from someone with more experience.
### How to Use the Socket MCP Server
When checking dependencies, make sure to also check the imports not just the pyproject.toml/package.json/dependency file.
```
1. **Ask your AI assistant** to check dependencies:
- "Check the security score for express version 4.18.2"
- "Analyze the security of my package.json dependencies"
- "What are the vulnerability scores for react, lodash, and axios?"
2. **Get comprehensive security insights** including supply chain, quality, maintenance, vulnerability, and license scores.
### Adjust tool usage with custom rules
You can further customize how the Socket MCP server interacts with your AI assistant by modifying your client rules. The rules are usually a markdown file and its location depends on the AI assistant you are using.
| MCP Client | Rules File Location |
|---|---|
| Claude Desktop/Code | `CLAUDE.md` |
| VSCode Copilot | `.github/copilot-instructions.md` |
| Cursor | `.cursor/rules` |
Rules that can be added to the client rules file include the following:
```md
Always check dependency scores with the depscore tool when you add a new dependency. If the score is low, consider using an alternative library or writing the code yourself. If you are unsure about the score, ask for a review from someone with more experience. When checking dependencies, make sure to also check the imports not just the pyproject.toml/package.json/dependency file.
```
You can adjust the rules to fit your needs. For example, you can add rules to include specific manifest files, or guide the AI assistant on how to handle low scores. The rules are flexible and can be tailored to your workflow.
## Development
### Prerequisites
### For End Users
For most users, we recommend using either:
1. **Public server**: `https://mcp.socket.dev/` (no setup required)
2. **NPX command**: `npx @socketsecurity/mcp@latest` (always latest version)
### For Contributors
If you want to contribute to the Socket MCP server development:
### Health Check Endpoint
When running in HTTP mode, the server provides a health check endpoint for Kubernetes and Docker deployments:
```bash
GET /health
```
**Response:**
```json
{
"status": "healthy",
"service": "socket-mcp",
"version": "0.0.3",
"timestamp": "2025-06-17T20:45:22.059Z"
}
```
This endpoint can be used for:
- Kubernetes liveness and readiness probes
- Docker health checks
- Load balancer health monitoring
- General service monitoring
#### Prerequisites
- Node.js v16 or higher
- npm or yarn
### Installation
#### Installation

@@ -141,3 +320,3 @@ Clone the repository and install dependencies:

## Build
#### Build

@@ -150,8 +329,6 @@ To build the project:

This compiles the TypeScript files and makes the binary executable called `socket-mcp`.
#### Run from Source
## Run
To run the Socket MCP server from source:
To run the Socket MCP server locally:
```bash

@@ -162,41 +339,37 @@ export SOCKET_API_KEY=your_api_key_here

After installing globally, you can run the executable directly:
Or in HTTP mode:
```bash
export SOCKET_API_KEY=your_api_key_here
socket-mcp
MCP_HTTP_MODE=true SOCKET_API_KEY=your_api_key_here node build/index.js --http
```
### Global Installation
## 🔧 Troubleshooting
To install the tool globally and make the `socket-mcp` command available system-wide:
### Common Issues
```bash
npm install -g .
```
**Q: The public server isn't responding**
- Check that you're using the correct URL: `https://mcp.socket.dev/`
- Verify your MCP client configuration is correct
- Try restarting your MCP client
After global installation, you can use the `socket-mcp` command from anywhere:
**Q: Local server fails to start**
- Ensure you have Node.js v16+ installed
- Check that your `SOCKET_API_KEY` environment variable is set
- Verify the API key has `packages:list` permission
```bash
export SOCKET_API_KEY=your_api_key_here
socket-mcp
```
**Q: Getting authentication errors with local server**
- Double-check your Socket API key is valid
- Ensure the key has the required `packages:list` scope
- Try regenerating your API key from the Socket dashboard
## Adjust tool usage with custom rules
**Q: AI assistant can't find the depscore tool**
- Restart your MCP client after configuration changes
- Verify the server configuration is saved correctly
- Check that the MCP server is running (for local deployments)
You can further customize how the Socket MCP server interacts with your AI assistant by modifying your client rules. The rules are usually a markdown file and its location depends on the AI assistant you are using.
### Getting Help
| MCP Client | Rules File Location |
|---|---|
| Claude Desktop/Code | `CLAUDE.md` |
| VSCode Copilot | `.github/copilot-instructions.md` |
| Cursor | `.cursor/rules` |
- 📖 [Socket Documentation](https://docs.socket.dev)
- 🐛 [Report Issues](https://github.com/SocketDev/socket-mcp/issues)
- 💬 [Community Support](https://github.com/SocketDev/socket-mcp/discussions)
Rules that can be added to the client rules file include the following:
```md
Always check dependency scores with the depscore tool when you add a new dependency. If the score is low, consider using an alternative library or writing the code yourself. If you are unsure about the score, ask for a review from someone with more experience. When checking dependencies, make sure to also check the imports not just the pyproject.toml/package.json/dependency file.
```
You can adjust the rules to fit your needs. For example, you can add rules to include specific manifest files, or guide the AI assistant on how to handle low scores. The rules are flexible and can be tailored to your workflow.

Sorry, the diff of this file is not supported yet