const require_chunk = require('./chunk-DWy1uDak.cjs');
const require_constants = require('./constants-DJrjLmh5.cjs');
const require_define = require('./define-BfP4rFlE.cjs');
const require_logging = require('./logging-CkAJKyq2.cjs');
const require_whoami = require('./whoami-DBlwuDZf.cjs');
const require_find_organizations = require('./find-organizations-BGI_WW2q.cjs');
const require_find_teams = require('./find-teams-BuH2ddaL.cjs');
const require_find_projects = require('./find-projects-B80qSPpP.cjs');
const require_find_releases = require('./find-releases-Cy-Q-Qje.cjs');
const require_get_issue_details = require('./get-issue-details-lQmdKAfJ.cjs');
const require_get_trace_details = require('./get-trace-details-iDp34mms.cjs');
const require_get_event_attachment = require('./get-event-attachment-CrtS0QRV.cjs');
const require_update_issue = require('./update-issue-eELBq_Uy.cjs');
const require_handler = require('./handler-TWOoomKr.cjs');
const require_create_team = require('./create-team-DmqKw2c1.cjs');
const require_create_project = require('./create-project-CZBklXm8.cjs');
const require_update_project = require('./update-project-DMRBdOZ5.cjs');
const require_create_dsn = require('./create-dsn-ggGt0lZf.cjs');
const require_find_dsns = require('./find-dsns-Ct6uFZMB.cjs');
const require_analyze_issue_with_seer = require('./analyze-issue-with-seer-CI8pvCnf.cjs');
const require_search_docs = require('./search-docs-CTT1Bt1U.cjs');
const require_get_doc = require('./get-doc-MxWNTA8R.cjs');
const require_handler$1 = require('./handler-Fsqncg_W.cjs');
const require_agent = require('./agent-DT4ic52w.cjs');
const require_error_handling = require('./error-handling-ZVmZRXZb.cjs');
const require_version = require('./version-CdN5Kpjv.cjs');
const require_permissions = require('./permissions-CpuEzSxz.cjs');
const require_constraint_helpers = require('./constraint-helpers-BJPdGLZ3.cjs');
const __modelcontextprotocol_sdk_server_mcp_js = require_chunk.__toESM(require("@modelcontextprotocol/sdk/server/mcp.js"));
const __sentry_core = require_chunk.__toESM(require("@sentry/core"));
const zod = require_chunk.__toESM(require("zod"));
const ai = require_chunk.__toESM(require("ai"));
const __modelcontextprotocol_sdk_inMemory_js = require_chunk.__toESM(require("@modelcontextprotocol/sdk/inMemory.js"));

//#region src/tools/use-sentry/handler.ts
/**
* Format tool calls into a readable trace
*/
function formatToolCallTrace(toolCalls) {
	let trace = "";
	for (let i = 0; i < toolCalls.length; i++) {
		const call = toolCalls[i];
		trace += `### ${i + 1}. ${call.toolName}\n\n`;
		const args = call.args;
		if (Object.keys(args).length === 0) trace += "_No arguments_\n\n";
		else {
			trace += "**Arguments:**\n```json\n";
			trace += JSON.stringify(args, null, 2);
			trace += "\n```\n\n";
		}
	}
	return trace;
}
var handler_default$2 = require_define.defineTool({
	name: "use_sentry",
	requiredScopes: [],
	description: [
		"Use Sentry's MCP Agent to answer questions related to Sentry (sentry.io).",
		"",
		"You should pass the entirety of the user's prompt to the agent. Do not interpret the prompt in any way. Just pass it directly to the agent.",
		""
	].join("\n"),
	inputSchema: {
		request: zod.z.string().trim().min(1).describe("The user's raw input. Do not interpret the prompt in any way. Do not add any additional information to the prompt."),
		trace: zod.z.boolean().optional().describe("Enable tracing to see all tool calls made by the agent. Useful for debugging.")
	},
	annotations: {
		readOnlyHint: true,
		openWorldHint: true
	},
	async handler(params, context) {
		const [clientTransport, serverTransport] = __modelcontextprotocol_sdk_inMemory_js.InMemoryTransport.createLinkedPair();
		const { use_sentry,...toolsForAgent } = tools_default;
		const server = buildServer({
			context,
			tools: toolsForAgent
		});
		await server.server.connect(serverTransport);
		const mcpClient = await (0, ai.experimental_createMCPClient)({
			name: "mcp.sentry.dev (use-sentry)",
			transport: clientTransport
		});
		try {
			const mcpTools = await mcpClient.tools();
			const agentResult = await require_agent.useSentryAgent({
				request: params.request,
				tools: mcpTools
			});
			let output = agentResult.result.result;
			if (params.trace && agentResult.toolCalls.length > 0) {
				output += "\n\n---\n\n## Tool Call Trace\n\n";
				output += formatToolCallTrace(agentResult.toolCalls);
			}
			return output;
		} finally {
			await mcpClient.close();
			await server.server.close();
		}
	}
});

//#endregion
//#region src/tools/index.ts
var tools_default = {
	whoami: require_whoami.whoami_default,
	find_organizations: require_find_organizations.find_organizations_default,
	find_teams: require_find_teams.find_teams_default,
	find_projects: require_find_projects.find_projects_default,
	find_releases: require_find_releases.find_releases_default,
	get_issue_details: require_get_issue_details.get_issue_details_default,
	get_trace_details: require_get_trace_details.get_trace_details_default,
	get_event_attachment: require_get_event_attachment.get_event_attachment_default,
	update_issue: require_update_issue.update_issue_default,
	search_events: require_handler.handler_default,
	create_team: require_create_team.create_team_default,
	create_project: require_create_project.create_project_default,
	update_project: require_update_project.update_project_default,
	create_dsn: require_create_dsn.create_dsn_default,
	find_dsns: require_find_dsns.find_dsns_default,
	analyze_issue_with_seer: require_analyze_issue_with_seer.analyze_issue_with_seer_default,
	search_docs: require_search_docs.search_docs_default,
	get_doc: require_get_doc.get_doc_default,
	search_issues: require_handler$1.handler_default,
	use_sentry: handler_default$2
};

//#endregion
//#region src/server.ts
/**
* Extracts MCP request parameters for OpenTelemetry attributes.
*
* @example Parameter Transformation
* ```typescript
* const input = { organizationSlug: "my-org", query: "is:unresolved" };
* const output = extractMcpParameters(input);
* // { "mcp.request.argument.organizationSlug": "\"my-org\"", "mcp.request.argument.query": "\"is:unresolved\"" }
* ```
*/
function extractMcpParameters(args) {
	return Object.fromEntries(Object.entries(args).map(([key, value]) => {
		return [`mcp.request.argument.${key}`, JSON.stringify(value)];
	}));
}
/**
* Creates and configures a complete MCP server with Sentry instrumentation.
*
* The server is built with tools filtered based on the granted scopes in the context.
* Context is captured in tool handler closures and passed directly to handlers.
*
* @example Usage with stdio transport
* ```typescript
* import { buildServer } from "@sentry/mcp-server/server";
* import { startStdio } from "@sentry/mcp-server/transports/stdio";
*
* const context = {
*   accessToken: process.env.SENTRY_TOKEN,
*   sentryHost: "sentry.io",
*   userId: "user-123",
*   clientId: "cursor-ide",
*   constraints: {}
* };
*
* const server = buildServer({ context });
* await startStdio(server, context);
* ```
*
* @example Usage with Cloudflare Workers
* ```typescript
* import { buildServer } from "@sentry/mcp-server/server";
* import { experimental_createMcpHandler as createMcpHandler } from "agents/mcp";
*
* const serverContext = buildContextFromOAuth();
* // Context is captured in closures during buildServer()
* const server = buildServer({ context: serverContext });
*
* // Context already available to tool handlers via closures
* return createMcpHandler(server, { route: "/mcp" })(request, env, ctx);
* ```
*/
function buildServer({ context, onToolComplete, tools: customTools }) {
	const server = new __modelcontextprotocol_sdk_server_mcp_js.McpServer({
		name: require_constants.MCP_SERVER_NAME,
		version: require_version.LIB_VERSION
	});
	configureServer({
		server,
		context,
		onToolComplete,
		tools: customTools
	});
	return (0, __sentry_core.wrapMcpServerWithSentry)(server);
}
/**
* Configures an MCP server with tools filtered by granted scopes.
*
* Internal function used by buildServer(). Use buildServer() instead for most cases.
* Tools are filtered at registration time based on grantedScopes, and context is
* captured in closures for tool handler execution.
*/
function configureServer({ server, context, onToolComplete, tools: customTools }) {
	const toolsToRegister = customTools ?? tools_default;
	const grantedScopes = context.grantedScopes ? new Set(context.grantedScopes) : new Set(require_constants.DEFAULT_SCOPES);
	server.server.onerror = (error) => {
		const transportLogOptions = {
			loggerScope: ["server", "transport"],
			contexts: { transport: { phase: "server.onerror" } }
		};
		require_logging.logIssue(error, transportLogOptions);
	};
	for (const [toolKey, tool] of Object.entries(toolsToRegister)) {
		if (!require_permissions.isToolAllowed(tool.requiredScopes, grantedScopes)) continue;
		const constraintKeysToFilter = new Set(require_constraint_helpers.getConstraintKeysToFilter(context.constraints, tool.inputSchema));
		const filteredInputSchema = Object.fromEntries(Object.entries(tool.inputSchema).filter(([key]) => !constraintKeysToFilter.has(key)));
		server.tool(tool.name, tool.description, filteredInputSchema, tool.annotations, async (params, extra) => {
			try {
				return await (0, __sentry_core.startNewTrace)(async () => {
					return await (0, __sentry_core.startSpan)({
						name: `tools/call ${tool.name}`,
						attributes: {
							"mcp.tool.name": tool.name,
							"mcp.server.name": require_constants.MCP_SERVER_NAME,
							"mcp.server.version": require_version.LIB_VERSION,
							...extractMcpParameters(params || {})
						}
					}, async (span) => {
						if (context.constraints.organizationSlug) span.setAttribute("sentry-mcp.constraint-organization", context.constraints.organizationSlug);
						if (context.constraints.projectSlug) span.setAttribute("sentry-mcp.constraint-project", context.constraints.projectSlug);
						if (context.userId) (0, __sentry_core.setUser)({ id: context.userId });
						if (context.clientId) (0, __sentry_core.setTag)("client.id", context.clientId);
						try {
							const applicableConstraints = require_constraint_helpers.getConstraintParametersToInject(context.constraints, tool.inputSchema);
							const paramsWithConstraints = {
								...params,
								...applicableConstraints
							};
							const output = await tool.handler(paramsWithConstraints, context);
							span.setStatus({ code: 1 });
							if (typeof output === "string") return { content: [{
								type: "text",
								text: output
							}] };
							if (Array.isArray(output)) return { content: output };
							throw new Error(`Invalid tool output: ${output}`);
						} catch (error) {
							span.setStatus({ code: 2 });
							return {
								content: [{
									type: "text",
									text: await require_error_handling.formatErrorForUser(error)
								}],
								isError: true
							};
						}
					});
				});
			} finally {
				onToolComplete?.();
			}
		});
	}
}

//#endregion
Object.defineProperty(exports, 'buildServer', {
  enumerable: true,
  get: function () {
    return buildServer;
  }
});
Object.defineProperty(exports, 'handler_default', {
  enumerable: true,
  get: function () {
    return handler_default$2;
  }
});
Object.defineProperty(exports, 'tools_default', {
  enumerable: true,
  get: function () {
    return tools_default;
  }
});
//# sourceMappingURL=server-J1RALwYS.cjs.map