opensecrets-mcp 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,3 +25,22 @@ The server uses stdio, so it can be connected to Claude Desktop, Cursor, VS Code
25
25
  ## Limits and privacy
26
26
 
27
27
  This project is intentionally narrow. It should be treated as a practical helper, not a complete certification or security audit. Check the implementation and the returned data before using it with sensitive material. Your key stays local and is only sent to OpenSecrets. Read-only.
28
+
29
+ <!-- paywall -->
30
+ ## Premium tools
31
+
32
+ These tools need a license key:
33
+
34
+ * `fec_candidate_search`
35
+ * `fec_committee_search`
36
+
37
+ Buy a key at https://mcp-marketplace.io/server/io-github-mrfentmen-opensecrets-mcp and set it in your MCP client config:
38
+
39
+ ```json
40
+ "env": { "MCP_LICENSE_KEY": "mcp_live_..." }
41
+ ```
42
+
43
+ The key is checked against MCP Marketplace, cached for 24 hours, and keeps
44
+ working offline once one check has succeeded. Every other tool on this server
45
+ stays free.
46
+ <!-- /paywall -->
package/dist/api.d.ts CHANGED
@@ -10,3 +10,14 @@ export interface Candidate {
10
10
  export declare function searchCandidates(query: string, cycle?: string): Promise<Candidate[]>;
11
11
  export declare function candidateSummary(cid: string, cycle?: string): Promise<string>;
12
12
  export declare function formatCandidate(c: Candidate, index?: number): string;
13
+ export declare function fecCandidateSearch(args: {
14
+ query: string;
15
+ office?: string;
16
+ state?: string;
17
+ party?: string;
18
+ limit?: number;
19
+ }): Promise<string>;
20
+ export declare function fecCommitteeSearch(args: {
21
+ query: string;
22
+ limit?: number;
23
+ }): Promise<string>;
package/dist/api.js CHANGED
@@ -61,3 +61,99 @@ export function formatCandidate(c, index) {
61
61
  const prefix = index !== undefined ? `${index + 1}. ` : "";
62
62
  return `${prefix}[${c.id ?? "?"}] ${c.name ?? "(unnamed)"}${c.party ? ` (${c.party}${c.state ? `-${c.state}` : ""})` : ""}${c.chamber ? ` — ${c.chamber}` : ""}`;
63
63
  }
64
+ // ---- muxB tools:
65
+ // OpenFEC, the FEC's own open API. DEMO_KEY is the placeholder the FEC
66
+ // documents for public use and reaches the candidate and committee indexes.
67
+ const FEC_BASE = "https://api.open.fec.gov/v1";
68
+ const FEC_DEMO_KEY = "DEMO_KEY";
69
+ async function fecGet(path, params = []) {
70
+ const qs = new URLSearchParams([...params, ["api_key", FEC_DEMO_KEY]]);
71
+ const res = await fetch(`${FEC_BASE}${path}?${qs.toString()}`, {
72
+ headers: { "User-Agent": "opensecrets-mcp/1.0", Accept: "application/json" },
73
+ signal: AbortSignal.timeout(25000),
74
+ });
75
+ if (res.status === 429)
76
+ throw new OpenSecretsError("OpenFEC DEMO_KEY is limited to 40 calls an hour; wait or register a key at api.data.gov.");
77
+ if (res.status === 422) {
78
+ const detail = (await res.json().catch(() => ({}))).message;
79
+ throw new OpenSecretsError(`OpenFEC rejected the query${detail ? `: ${String(detail).slice(0, 200)}` : "."}`);
80
+ }
81
+ if (!res.ok)
82
+ throw new OpenSecretsError(`OpenFEC error ${res.status}`);
83
+ return (await res.json());
84
+ }
85
+ function fecCycles(row) {
86
+ const list = Array.isArray(row.cycles) ? row.cycles : [];
87
+ if (list.length === 0)
88
+ return "cycles not reported";
89
+ const shown = list.slice(0, 6).map(String);
90
+ return shown.join(", ") + (list.length > 6 ? `, +${list.length - 6} more` : "");
91
+ }
92
+ function fecCommitteeLine(c) {
93
+ const designation = c.designation_full ?? c.designation ?? "";
94
+ return ` ${c.committee_id ?? "?"} ${c.name ?? "(unnamed)"}${designation ? ` [${designation}]` : ""}${c.committee_type_full ? ` (${c.committee_type_full})` : ""}`;
95
+ }
96
+ export async function fecCandidateSearch(args) {
97
+ const q = (args.query ?? "").trim();
98
+ if (!q)
99
+ throw new OpenSecretsError("Query is empty.");
100
+ const limit = Math.min(Math.max(args.limit ?? 5, 1), 20);
101
+ const params = [["q", q], ["per_page", String(limit)], ["sort", "-receipts"]];
102
+ const office = (args.office ?? "").trim().toUpperCase();
103
+ if (office)
104
+ params.push(["office", office]);
105
+ const state = (args.state ?? "").trim().toUpperCase();
106
+ if (state)
107
+ params.push(["state", state]);
108
+ const party = (args.party ?? "").trim().toUpperCase();
109
+ if (party)
110
+ params.push(["party", party]);
111
+ const data = await fecGet("/candidates/search/", params);
112
+ const rows = Array.isArray(data.results) ? data.results : [];
113
+ if (rows.length === 0)
114
+ return `No FEC candidate records match "${q}".`;
115
+ const total = (data.pagination ?? {}).count;
116
+ return [
117
+ `FEC candidate index for "${q}"${office ? `, office ${office}` : ""}${state ? `, ${state}` : ""}${party ? `, ${party}` : ""} - ${Number(total ?? 0).toLocaleString()} match, showing ${rows.length}:`,
118
+ ...rows.map((r, i) => {
119
+ const committees = Array.isArray(r.principal_committees) ? r.principal_committees : [];
120
+ return [
121
+ `${i + 1}. ${r.name ?? "(unnamed)"} [${r.candidate_id ?? "?"}]`,
122
+ ` ${r.office_full ?? r.office ?? "office not reported"}${r.district && r.district !== "00" ? `-${r.district}` : ""} · ${r.state ?? "?"} · ${r.party_full ?? r.party ?? "party not reported"}`,
123
+ ` status ${r.candidate_status ?? "not reported"}${r.incumbent_challenge_full ? `, ${r.incumbent_challenge_full}` : ""} · raised funds: ${r.has_raised_funds === true ? "yes" : r.has_raised_funds === false ? "no" : "not reported"}`,
124
+ ` cycles: ${fecCycles(r)}`,
125
+ committees.length ? ` principal committees:` : " principal committees: not reported",
126
+ ...committees.slice(0, 3).map(fecCommitteeLine),
127
+ committees.length > 3 ? ` ...and ${committees.length - 3} more committees` : "",
128
+ ].filter(Boolean).join("\n");
129
+ }),
130
+ ].join("\n");
131
+ }
132
+ export async function fecCommitteeSearch(args) {
133
+ const q = (args.query ?? "").trim();
134
+ if (!q)
135
+ throw new OpenSecretsError("Query is empty.");
136
+ const limit = Math.min(Math.max(args.limit ?? 5, 1), 20);
137
+ const data = await fecGet("/committees/", [["q", q], ["per_page", String(limit)], ["sort", "-receipts"]]);
138
+ const rows = Array.isArray(data.results) ? data.results : [];
139
+ if (rows.length === 0)
140
+ return `No FEC committees match "${q}".`;
141
+ const total = (data.pagination ?? {}).count;
142
+ return [
143
+ `FEC committee index for "${q}" - ${Number(total ?? 0).toLocaleString()} match, showing ${rows.length}:`,
144
+ ...rows.map((r, i) => {
145
+ const agent = [r.designated_agent_name, r.designated_agent_city, r.designated_agent_state].filter(Boolean).join(", ");
146
+ const sponsor = Array.isArray(r.sponsor_candidate_list) ? r.sponsor_candidate_list.map((s) => String(s.name ?? s.candidate_id ?? "?")) : [];
147
+ const candidates = Array.isArray(r.candidate_ids) ? r.candidate_ids.map(String) : [];
148
+ return [
149
+ `${i + 1}. ${r.name ?? "(unnamed committee)"} [${r.committee_id ?? "?"}]`,
150
+ ` ${r.committee_type_full ?? "type not reported"}${r.designation_full ? ` · ${r.designation_full}` : ""}${r.party_full ? ` · ${r.party_full}` : ""}${r.state ? ` · ${r.state}` : ""}`,
151
+ ` treasurer ${r.treasurer_name ?? "not reported"}${agent ? ` (designated agent ${agent})` : ""} · filing ${r.filing_frequency ?? "not reported"}`,
152
+ ` cycles: ${fecCycles(r)} · first file ${r.first_file_date ?? "not reported"} · last file ${r.last_file_date ?? "not reported"}`,
153
+ sponsor.length ? ` sponsored by: ${sponsor.slice(0, 3).join(", ")}${sponsor.length > 3 ? `, +${sponsor.length - 3} more` : ""}` : "",
154
+ candidates.length ? ` linked candidate ids: ${candidates.slice(0, 4).join(", ")}${candidates.length > 4 ? `, +${candidates.length - 4} more` : ""}` : "",
155
+ r.affiliated_committee_name ? ` affiliated with: ${r.affiliated_committee_name}` : "",
156
+ ].filter(Boolean).join("\n");
157
+ }),
158
+ ].join("\n");
159
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Returns null when the caller may run the tool, or a short message telling
3
+ * them how to get a key.
4
+ *
5
+ * A good key is remembered for an hour, so a busy session does not hit the
6
+ * license server on every call and keeps working through a brief outage.
7
+ */
8
+ export declare function premiumRequired(tool: string): Promise<string | null>;
@@ -0,0 +1,79 @@
1
+ // Premium tools on this server need a license key bought from MCP Marketplace.
2
+ // Buyers put the key in their MCP client config as MCP_LICENSE_KEY. Every tool
3
+ // that is not listed in PREMIUM keeps working without a key.
4
+ const SLUG = "opensecrets-mcp";
5
+ // Tools that need a key. Everything else is free.
6
+ const PREMIUM = new Set([
7
+ "fec_candidate_search",
8
+ "fec_committee_search",
9
+ ]);
10
+ const BUY_URL = `https://mcp-marketplace.io/server/io-github-mrfentmen-${SLUG}`;
11
+ // The license check calls the marketplace's verify endpoint directly instead of
12
+ // using @mcp_marketplace/license. That SDK sends no `apikey` header, so every
13
+ // check it makes is rejected by Supabase before it reaches the function. The
14
+ // publishable key below is public by design - it ships in mcp-marketplace.io's
15
+ // own JavaScript and only ever reaches their licence check.
16
+ const DEFAULT_VERIFY_URL = "https://virupvwhtkpkjsiskckg.supabase.co/functions/v1/verify-key";
17
+ const PUBLISHABLE_KEY = "sb_publishable_BuqlW96Ke8C_zzJG-LQv1Q_YHi_r_4h";
18
+ const OK_CACHE_MS = 60 * 60 * 1000;
19
+ const BAD_CACHE_MS = 60 * 1000;
20
+ const seen = new Map();
21
+ const REASONS = {
22
+ missing_key: "no key is set",
23
+ invalid_format: "that key is not a valid MCP Marketplace key",
24
+ not_found: "that key was not found",
25
+ revoked: "that key has been revoked",
26
+ rotated: "that key was rotated, use your new one",
27
+ expired: "that key has expired, renew it",
28
+ rate_limited: "there were too many checks just now, try again shortly",
29
+ network_error: "the license server could not be reached",
30
+ };
31
+ function blocked(tool, reason) {
32
+ const why = REASONS[reason] ?? `the license server answered "${reason}"`;
33
+ return `"${tool}" needs a license key, but ${why}. ` +
34
+ `Set MCP_LICENSE_KEY in your MCP client config. Get a key: ${BUY_URL}`;
35
+ }
36
+ async function verify(key) {
37
+ const res = await fetch(process.env.MCP_LICENSE_VERIFY_URL || DEFAULT_VERIFY_URL, {
38
+ method: "POST",
39
+ headers: {
40
+ apikey: PUBLISHABLE_KEY,
41
+ Authorization: `Bearer ${PUBLISHABLE_KEY}`,
42
+ "Content-Type": "application/json",
43
+ },
44
+ body: JSON.stringify({ key, slug: SLUG }),
45
+ // an unusable key answers 400 with a JSON body, so read the body either way
46
+ signal: AbortSignal.timeout(15000),
47
+ });
48
+ const data = (await res.json());
49
+ if (typeof data?.valid !== "boolean")
50
+ return { valid: false, reason: "unexpected_response" };
51
+ return data;
52
+ }
53
+ /**
54
+ * Returns null when the caller may run the tool, or a short message telling
55
+ * them how to get a key.
56
+ *
57
+ * A good key is remembered for an hour, so a busy session does not hit the
58
+ * license server on every call and keeps working through a brief outage.
59
+ */
60
+ export async function premiumRequired(tool) {
61
+ if (!PREMIUM.has(tool))
62
+ return null;
63
+ const key = process.env.MCP_LICENSE_KEY;
64
+ if (!key)
65
+ return blocked(tool, "missing_key");
66
+ const hit = seen.get(key);
67
+ if (hit && Date.now() - hit.at < (hit.valid ? OK_CACHE_MS : BAD_CACHE_MS)) {
68
+ return hit.valid ? null : blocked(tool, hit.reason ?? "invalid");
69
+ }
70
+ let result;
71
+ try {
72
+ result = await verify(key);
73
+ }
74
+ catch {
75
+ result = { valid: false, reason: "network_error" };
76
+ }
77
+ seen.set(key, { ...result, at: Date.now() });
78
+ return result.valid ? null : blocked(tool, result.reason ?? "invalid");
79
+ }
package/dist/server.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { z } from "zod";
3
- import { candidateSummary, formatCandidate, OpenSecretsError, searchCandidates } from "./api.js";
3
+ import { candidateSummary, formatCandidate, OpenSecretsError, searchCandidates, fecCandidateSearch, fecCommitteeSearch } from "./api.js";
4
+ import { premiumRequired } from "./license.js";
4
5
  const text = (t) => ({ content: [{ type: "text", text: t }] });
5
6
  const textError = (t) => ({ content: [{ type: "text", text: t }], isError: true });
6
7
  const READ_ONLY = { readOnlyHint: true, openWorldHint: true };
@@ -43,6 +44,51 @@ export function createServer() {
43
44
  return textError(errorMessage(e));
44
45
  }
45
46
  });
47
+ server.registerTool("fec_candidate_search", {
48
+ title: "Search the FEC candidate index",
49
+ description: "Federal campaign-finance candidate index by name fragment, with office, state and party filters, plus each candidate's principal committees and cycle history.",
50
+ inputSchema: z.object({
51
+ query: z.string().describe("Name fragment, e.g. 'Sanders'"),
52
+ office: z.string().default("").describe("Office code: H for House, S for Senate, P for President, empty = all"),
53
+ state: z.string().default("").describe("Two-letter state or 'US', empty = all"),
54
+ party: z.string().default("").describe("DEM, REP, IND or empty = all"),
55
+ limit: z.number().int().min(1).max(20).default(5),
56
+ }),
57
+ annotations: READ_ONLY,
58
+ }, async ({ query, office, state, party, limit }) => {
59
+ // ---- paywall: fec_candidate_search ----
60
+ const paywallMessage = await premiumRequired("fec_candidate_search");
61
+ if (paywallMessage)
62
+ return { content: [{ type: "text", text: paywallMessage }], isError: true };
63
+ // ---- paywall: end ----
64
+ try {
65
+ return text(await fecCandidateSearch({ query, office, state, party, limit }));
66
+ }
67
+ catch (e) {
68
+ return textError(errorMessage(e));
69
+ }
70
+ });
71
+ server.registerTool("fec_committee_search", {
72
+ title: "Search the FEC committee index",
73
+ description: "Federal campaign committees by name keyword: type, designation, party, treasurer, filing frequency, cycle span and sponsored candidates.",
74
+ inputSchema: z.object({
75
+ query: z.string().describe("Committee name fragment, e.g. 'for Senate'"),
76
+ limit: z.number().int().min(1).max(20).default(5),
77
+ }),
78
+ annotations: READ_ONLY,
79
+ }, async ({ query, limit }) => {
80
+ // ---- paywall: fec_committee_search ----
81
+ const paywallMessage = await premiumRequired("fec_committee_search");
82
+ if (paywallMessage)
83
+ return { content: [{ type: "text", text: paywallMessage }], isError: true };
84
+ // ---- paywall: end ----
85
+ try {
86
+ return text(await fecCommitteeSearch({ query, limit }));
87
+ }
88
+ catch (e) {
89
+ return textError(errorMessage(e));
90
+ }
91
+ });
46
92
  return server;
47
93
  }
48
94
  function errorMessage(e) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opensecrets-mcp",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "MCP server for OpenSecrets: money in U.S. politics. Needs a free API key.",
5
5
  "type": "module",
6
6
  "mcpName": "io.github.mrfentmen/opensecrets-mcp",