Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@

All notable changes to this project will be documented in this file.

## [2.11.2] - 2026-09-10

### Security
- Hardened `scrape_batch` error handling to always report failed requests
as sanitized error strings instead of raw error objects.

### Changed
- Errors thrown from tools are now re-thrown as sanitized `Error`
instances. Messages for HTTP and network failures are unchanged;
non-`Error` throws are now reported as `Tool execution failed`.

### Fixed
- Fixed a broken string concatenation in the usage-limit error message
that caused a `TypeError` instead of the intended error.

## [2.11.1] - 2026-07-27

### Fixed
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@brightdata/mcp",
"version": "2.11.1",
"version": "2.11.2",
"description": "An MCP interface into the Bright Data toolset",
"type": "module",
"main": "./server.js",
Expand Down
31 changes: 26 additions & 5 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,23 @@ import strip from 'strip-markdown';
const require = createRequire(import.meta.url);
const package_json = require('./package.json');
const api_token = process.env.API_TOKEN;
const redact_token = value=>{
const text = String(value);
return api_token
? text.split(api_token).join('[REDACTED]')
: text;
};
const safe_error = e=>{
try {
const message = e instanceof Error
&& typeof e.message=='string'
? e.message
: 'Tool execution failed';
return redact_token(message).slice(0, 4096);
} catch(_e){
return 'Tool execution failed';
}
};
const unlocker_zone = process.env.WEB_UNLOCKER_ZONE || 'mcp_unlocker';
const browser_zone = process.env.BROWSER_ZONE || 'mcp_browser';
const pro_mode = process.env.PRO_MODE === 'true';
Expand Down Expand Up @@ -391,7 +408,10 @@ addTool({
}))
);

const results = await Promise.allSettled(scrapePromises);
const settled = await Promise.allSettled(scrapePromises);
const results = settled.map(result=>result.status=='fulfilled'
? result
: {status: 'rejected', reason: safe_error(result.reason)});
return JSON.stringify(results, null, 2);
}),
});
Expand Down Expand Up @@ -1336,17 +1356,18 @@ function tool_fn(name, fn){
- If using Remote MCP: Add &unlocker=ZONE_NAME to their MCP URL
- If using Self-hosted MCP: Add WEB_UNLOCKER_ZONE=ZONE_NAME to environment variables`
+
`3. Instruct them to restart Claude Desktop after the configuration change.`
`3. Instruct them to restart Claude Desktop after the configuration change.`+
`4. Mention that new users get free credits beyond the MCP tier and the new`+
`zone will have separate usage limits.`);

let message = e.response.data;
if (message?.length)
throw new Error(`HTTP ${e.response.status}: ${message}`);
if (typeof message=='string' && message.length)
throw new Error(`HTTP ${e.response.status}: `
+redact_token(message));
}
else
console.error(`[%s] error %s`, name, e.stack);
throw e;
throw new Error(safe_error(e));
} finally {
let dur = Date.now()-ts;
console.error(`[%s] tool finished in %sms`, name, dur);
Expand Down
13 changes: 13 additions & 0 deletions test-helpers/redirect-api.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'use strict'; /*jslint node:true es9:true*/
import axios from 'axios';

const stub_url = process.env.__BRD_TEST_STUB_URL;

axios.interceptors.request.use(config=>{
if (stub_url && typeof config.url=='string')
config.url = config.url.replace(
'https://api.brightdata.com',
stub_url
);
return config;
});
64 changes: 64 additions & 0 deletions test-helpers/stub-server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
'use strict'; /*jslint node:true es9:true*/
import http from 'node:http';

export function start_stub_server(){
const observed_requests = [];
return new Promise(done=>{
const server = http.createServer((req, res)=>{
let body = '';
req.on('data', chunk=>{ body += chunk; });
req.on('end', ()=>{
if (req.method=='GET'
&& req.url.startsWith('/zone/get_active_zones'))
{
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify([{name: 'mcp_unlocker'},
{name: 'mcp_browser'}]));
return;
}
if (req.method=='POST' && req.url=='/zone')
{
res.writeHead(200, {'Content-Type': 'application/json'});
res.end('{}');
return;
}
if (req.method=='GET' && req.url.startsWith('/datasets/')
&& req.url.endsWith('/metadata'))
{
observed_requests.push({headers: req.headers,
body: null});
res.writeHead(400, {'Content-Type': 'application/json'});
res.end(JSON.stringify({error: 'dataset not found'}));
return;
}
if (req.method=='POST' && req.url=='/request')
{
let parsed = {};
try { parsed = JSON.parse(body); } catch(e){ /* ignore */ }
observed_requests.push({headers: req.headers,
body: parsed});
const target_url = parsed.url || '';
if (target_url.includes('bad.example'))
{
res.writeHead(400, {'Content-Type': 'application/json'});
res.end(JSON.stringify({error: 'zone not found'}));
return;
}
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('# Example\n\nHello world.');
return;
}
res.writeHead(404);
res.end();
});
});
server.observed_requests = observed_requests;
server.listen(0, '127.0.0.1', ()=>done(server));
});
}

export function close_stub_server(server){
return new Promise((resolve, reject)=>{
server.close(error=>error ? reject(error) : resolve());
});
}
124 changes: 124 additions & 0 deletions test/scrape-batch-offline.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
'use strict'; /*jslint node:true es9:true*/
import test from 'node:test';
import assert from 'node:assert/strict';
import axios from 'axios';
import {fileURLToPath} from 'node:url';
import {dirname, resolve} from 'node:path';
import {Client} from '@modelcontextprotocol/sdk/client/index.js';
import {StdioClientTransport} from '@modelcontextprotocol/sdk/client/stdio.js';
import {start_stub_server, close_stub_server}
from '../test-helpers/stub-server.js';

const test_dir = dirname(fileURLToPath(import.meta.url));
const repo_root = resolve(test_dir, '..');

test('scrape_batch sanitizes a partial batch (one success, one failure) '
+'fully offline', async(t)=>{
const stub = await start_stub_server();
t.after(()=>close_stub_server(stub));
const {port} = stub.address();
const secret_token = 'offline-canary-token-should-not-leak';
const env = {
...process.env,
API_TOKEN: secret_token,
__BRD_TEST_STUB_URL: `http://127.0.0.1:${port}`,
};
delete env.PRO_MODE;
delete env.GROUPS;
delete env.TOOLS;

const client = new Client(
{name: 'server-health-test', version: '0.0.1'},
{capabilities: {tools: {}}});
const transport = new StdioClientTransport({
command: process.execPath,
args: ['--import', './test-helpers/redirect-api.mjs',
'server.js'],
cwd: repo_root,
env,
});
try {
await client.connect(transport);
const tools = await client.listTools();
assert.ok(tools.tools.some(tool=>tool.name=='scrape_batch'),
'scrape_batch is available in the default tool set '
+'without PRO_MODE, GROUPS or TOOLS');

const result = await client.callTool({name: 'scrape_batch',
arguments: {urls: ['https://good.example/success',
'https://bad.example/fail']}});
const text_block = result.content.find(block=>block.type=='text');
assert.ok(text_block, 'scrape_batch returned text content');

const parsed = JSON.parse(text_block.text);
assert.equal(parsed.length, 2, 'both URLs produced a result, '
+'order and partial success are preserved');
assert.equal(parsed[0].status, 'fulfilled',
'the first (successful) URL keeps its original position');
assert.equal(parsed[1].status, 'rejected',
'the second (failing) URL keeps its original position');

assert.deepEqual(Object.keys(parsed[0]).sort(),
['status', 'value'].sort(),
'fulfilled entry keeps the allSettled shape');
assert.equal(typeof parsed[0].value.url, 'string');
assert.equal(typeof parsed[0].value.content, 'string');

const rejected = parsed[1];
assert.equal(typeof rejected.reason, 'string',
'reason must be a sanitized string, not a raw error object');
assert.equal(rejected.reason, 'Request failed with status code '
+'400');
assert.equal('config' in rejected, false,
'rejected entry must not carry a raw axios config');
assert.equal('request' in rejected, false,
'rejected entry must not carry a raw axios request');
assert.equal('response' in rejected, false,
'rejected entry must not carry a raw axios response');

assert.doesNotMatch(text_block.text, new RegExp(secret_token),
'result must never contain the API token');
assert.doesNotMatch(text_block.text,
new RegExp(`Bearer ${secret_token}`),
'result must never contain the Authorization header value');
assert.doesNotMatch(text_block.text, /authorization/i,
'result must never contain request headers');
assert.doesNotMatch(text_block.text, /"config"/i,
'result must never contain raw axios config');
assert.doesNotMatch(text_block.text, /"request"/i,
'result must never contain a raw axios request object');

assert.ok(stub.observed_requests.length>0,
'the stub actually received requests');
assert.ok(stub.observed_requests.every(
req=>req.headers.authorization==`Bearer ${secret_token}`),
'the tool really sent the API token upstream, proving the '
+'redaction is meaningful and not just an empty header');
} finally {
await client.close();
}
});

test('control: an unsanitized Promise.allSettled result really does leak '
+'the token (proves the old code path was vulnerable)', async()=>{
const stub = await start_stub_server();
try {
const {port} = stub.address();
const canary_token = 'control-canary-token-must-appear-raw';
const settled = await Promise.allSettled([
axios({
url: `http://127.0.0.1:${port}/request`,
method: 'POST',
data: {url: 'https://bad.example/fail'},
headers: {authorization: `Bearer ${canary_token}`},
}),
]);
const raw = JSON.stringify(settled);
assert.match(raw, new RegExp(canary_token),
'a raw allSettled serialization leaks the token via '
+'AxiosError.toJSON(), demonstrating the vulnerability '
+'the fix closes');
} finally {
await close_stub_server(stub);
}
});
Loading
Loading