basecamp-mcp 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,4 @@
1
+ """Basecamp MCP server for Claude."""
2
+
3
+ __version__ = "0.1.0"
4
+ USER_AGENT = "Basecamp MCP Server (https://github.com/jacobfiler/basecamp-mcp)"
basecamp_mcp/auth.py ADDED
@@ -0,0 +1,353 @@
1
+ """OAuth flow for Basecamp — browser-based authorization with local callback server."""
2
+
3
+ import http.server
4
+ import sys
5
+ import urllib.parse
6
+ import webbrowser
7
+
8
+ import httpx
9
+
10
+ from . import USER_AGENT
11
+ from .config import load_config, save_config, update_doc_search
12
+
13
+ REDIRECT_URI = "http://localhost:8000/callback"
14
+ AUTH_BASE = "https://launchpad.37signals.com"
15
+
16
+
17
+ def run_auth_flow() -> None:
18
+ """Interactive OAuth flow: prompt for credentials, open browser, catch callback."""
19
+ print("=" * 60)
20
+ print("Basecamp MCP — OAuth Setup")
21
+ print("=" * 60)
22
+ print()
23
+ print("You need a Basecamp OAuth app to continue.")
24
+ print("If you already have one, skip to entering your Client ID below.")
25
+ print()
26
+ print("To register a new app:")
27
+ print(" 1. Go to https://launchpad.37signals.com/integrations")
28
+ print(" (Log in with your Basecamp account)")
29
+ print(' 2. Click "Register another application"')
30
+ print(" 3. Fill in the form:")
31
+ print(" - Name: Basecamp MCP (or anything you like)")
32
+ print(" - Company: Your company name")
33
+ print(" - Website: https://github.com/jacobfiler/basecamp-mcp")
34
+ print(f" - Redirect URI: {REDIRECT_URI} <-- must be exact")
35
+ print(' 4. Click "Register this app"')
36
+ print(" 5. Copy the Client ID and Client Secret shown on the next page")
37
+ print()
38
+
39
+ client_id = input("Client ID: ").strip()
40
+ if not client_id:
41
+ print("Client ID is required.")
42
+ sys.exit(1)
43
+
44
+ client_secret = input("Client Secret: ").strip()
45
+ if not client_secret:
46
+ print("Client Secret is required.")
47
+ sys.exit(1)
48
+
49
+ auth_url = (
50
+ f"{AUTH_BASE}/authorization/new"
51
+ f"?type=web_server"
52
+ f"&client_id={client_id}"
53
+ f"&redirect_uri={urllib.parse.quote(REDIRECT_URI)}"
54
+ )
55
+
56
+ # State to capture from callback
57
+ result: dict = {}
58
+
59
+ class CallbackHandler(http.server.BaseHTTPRequestHandler):
60
+ def do_GET(self):
61
+ query = urllib.parse.urlparse(self.path).query
62
+ params = urllib.parse.parse_qs(query)
63
+
64
+ if "code" not in params:
65
+ error = params.get("error", ["unknown"])[0]
66
+ result["error"] = error
67
+ self.send_response(400)
68
+ self.end_headers()
69
+ self.wfile.write(f"Authorization failed: {error}".encode())
70
+ return
71
+
72
+ code = params["code"][0]
73
+ print("\nGot authorization code, exchanging for tokens...")
74
+
75
+ # Exchange code for tokens
76
+ try:
77
+ response = httpx.post(
78
+ f"{AUTH_BASE}/authorization/token",
79
+ params={
80
+ "type": "web_server",
81
+ "client_id": client_id,
82
+ "client_secret": client_secret,
83
+ "redirect_uri": REDIRECT_URI,
84
+ "code": code,
85
+ },
86
+ timeout=30.0,
87
+ )
88
+ response.raise_for_status()
89
+ result["tokens"] = response.json()
90
+ except httpx.HTTPError as e:
91
+ result["error"] = str(e)
92
+ self.send_response(500)
93
+ self.end_headers()
94
+ self.wfile.write(b"Token exchange failed. Check terminal.")
95
+ return
96
+
97
+ self.send_response(200)
98
+ self.send_header("Content-type", "text/html")
99
+ self.end_headers()
100
+ self.wfile.write(
101
+ b"<h1>Authorized!</h1>"
102
+ b"<p>You can close this window. Check your terminal.</p>"
103
+ )
104
+
105
+ def log_message(self, format, *args):
106
+ pass
107
+
108
+ print("\nOpening browser for authorization...")
109
+ print("(If it doesn't open, visit this URL manually:)")
110
+ print(f" {auth_url}")
111
+ print()
112
+
113
+ webbrowser.open(auth_url)
114
+
115
+ server = http.server.HTTPServer(("localhost", 8000), CallbackHandler)
116
+ server.handle_request()
117
+
118
+ if "error" in result:
119
+ print(f"\nAuthorization failed: {result['error']}")
120
+ sys.exit(1)
121
+
122
+ tokens = result["tokens"]
123
+ access_token = tokens["access_token"]
124
+ refresh_token = tokens.get("refresh_token", "")
125
+
126
+ # Discover account(s) and user identity
127
+ print("Fetching account info...")
128
+ try:
129
+ response = httpx.get(
130
+ "https://launchpad.37signals.com/authorization.json",
131
+ headers={
132
+ "Authorization": f"Bearer {access_token}",
133
+ "User-Agent": USER_AGENT,
134
+ },
135
+ timeout=30.0,
136
+ )
137
+ response.raise_for_status()
138
+ auth_data = response.json()
139
+ except httpx.HTTPError as e:
140
+ print(f"\nFailed to fetch account info: {e}")
141
+ sys.exit(1)
142
+
143
+ identity = auth_data.get("identity", {})
144
+ user_name = (
145
+ f"{identity.get('first_name', '')} {identity.get('last_name', '')}".strip()
146
+ )
147
+ user_email = identity.get("email_address", "")
148
+
149
+ # Filter to Basecamp 3 accounts only
150
+ accounts = [a for a in auth_data.get("accounts", []) if a.get("product") == "bc3"]
151
+
152
+ if not accounts:
153
+ print("\nNo Basecamp 3 accounts found for this user.")
154
+ sys.exit(1)
155
+
156
+ if len(accounts) == 1:
157
+ account = accounts[0]
158
+ else:
159
+ print(f"\nFound {len(accounts)} Basecamp accounts:")
160
+ for i, a in enumerate(accounts, 1):
161
+ print(f" {i}. {a['name']} (ID: {a['id']})")
162
+ while True:
163
+ choice = input(f"\nSelect account [1-{len(accounts)}]: ").strip()
164
+ try:
165
+ idx = int(choice) - 1
166
+ if 0 <= idx < len(accounts):
167
+ account = accounts[idx]
168
+ break
169
+ except ValueError:
170
+ pass
171
+ print("Invalid selection.")
172
+
173
+ config = {
174
+ "client_id": client_id,
175
+ "client_secret": client_secret,
176
+ "access_token": access_token,
177
+ "refresh_token": refresh_token,
178
+ "account_id": str(account["id"]),
179
+ "account_name": account["name"],
180
+ "user_name": user_name,
181
+ "user_email": user_email,
182
+ }
183
+
184
+ save_config(config)
185
+
186
+ # Auto-configure Claude Desktop
187
+ _configure_claude_desktop()
188
+
189
+ print()
190
+ print("=" * 60)
191
+ print("Setup complete!")
192
+ print("=" * 60)
193
+ print(f" Account: {account['name']} (ID: {account['id']})")
194
+ print(f" User: {user_name} ({user_email})")
195
+ print()
196
+ print("Basecamp tools are now available in Claude Desktop.")
197
+ print("Restart Claude Desktop if it's currently running.")
198
+ print()
199
+
200
+ # Offer document search setup
201
+ _offer_doc_search_setup()
202
+
203
+
204
+ def run_connect_docs() -> None:
205
+ """Standalone command to connect a document search API."""
206
+ config = load_config()
207
+ if not config:
208
+ print("Run `basecamp-mcp auth` first to set up Basecamp access.")
209
+ sys.exit(1)
210
+
211
+ print("=" * 60)
212
+ print("Basecamp MCP — Document Search Setup")
213
+ print("=" * 60)
214
+ print()
215
+ _prompt_doc_search()
216
+
217
+
218
+ def _offer_doc_search_setup() -> None:
219
+ """Ask at end of auth flow whether to connect document search."""
220
+ print("-" * 60)
221
+ print("Optional: Connect a document search API")
222
+ print("-" * 60)
223
+ print()
224
+ print("If your organization has a document ingestion service")
225
+ print("(e.g. one that indexes .docx files from Basecamp),")
226
+ print("you can connect it now to enable full-text document search.")
227
+ print()
228
+
229
+ answer = input("Connect a document search API? (y/N): ").strip().lower()
230
+ if answer not in ("y", "yes"):
231
+ print("Skipped. You can add this later with `basecamp-mcp connect-docs`.")
232
+ return
233
+
234
+ print()
235
+ _prompt_doc_search()
236
+
237
+
238
+ def _prompt_doc_search() -> None:
239
+ """Prompt for document search URL + token, validate, and save."""
240
+ print("Enter the URL of your document search API.")
241
+ print("This should be the base URL (e.g. https://your-app.ondigitalocean.app)")
242
+ print()
243
+
244
+ url = input("Document search API URL: ").strip()
245
+ if not url:
246
+ print("URL is required.")
247
+ sys.exit(1)
248
+
249
+ url = url.rstrip("/")
250
+
251
+ print()
252
+ print("If the API requires authentication, enter the Bearer token.")
253
+ print("Leave blank if no authentication is needed.")
254
+ print()
255
+
256
+ token = input("API token (optional): ").strip() or None
257
+
258
+ # Validate the connection
259
+ print("\nTesting connection...")
260
+ headers = {"User-Agent": USER_AGENT}
261
+ if token:
262
+ headers["Authorization"] = f"Bearer {token}"
263
+
264
+ try:
265
+ response = httpx.get(
266
+ f"{url}/api/documents/stats",
267
+ headers=headers,
268
+ timeout=15.0,
269
+ )
270
+ response.raise_for_status()
271
+ stats = response.json()
272
+ except httpx.ConnectError:
273
+ print(f"\nCould not connect to {url}")
274
+ print("Check the URL and make sure the service is running.")
275
+ sys.exit(1)
276
+ except httpx.HTTPStatusError as e:
277
+ print(f"\nConnection failed: HTTP {e.response.status_code}")
278
+ if e.response.status_code == 401:
279
+ print("Authentication failed — check your API token.")
280
+ sys.exit(1)
281
+ except httpx.HTTPError as e:
282
+ print(f"\nConnection failed: {e}")
283
+ sys.exit(1)
284
+
285
+ doc_count = stats.get("total_documents", stats.get("count", "?"))
286
+ update_doc_search(url, token)
287
+
288
+ print()
289
+ print(f"Connected! {doc_count} documents indexed.")
290
+ print("Document search tools are now available in Claude.")
291
+ print()
292
+
293
+
294
+ def _configure_claude_desktop() -> None:
295
+ """Auto-add basecamp MCP server to Claude Desktop config."""
296
+ import json
297
+ import platform
298
+ import shutil
299
+ from pathlib import Path
300
+
301
+ system = platform.system()
302
+ if system == "Darwin":
303
+ config_path = (
304
+ Path.home()
305
+ / "Library"
306
+ / "Application Support"
307
+ / "Claude"
308
+ / "claude_desktop_config.json"
309
+ )
310
+ elif system == "Windows":
311
+ import os
312
+
313
+ appdata = Path(os.environ.get("APPDATA", ""))
314
+ config_path = appdata / "Claude" / "claude_desktop_config.json"
315
+ else:
316
+ config_path = Path.home() / ".config" / "Claude" / "claude_desktop_config.json"
317
+
318
+ # Find the executable — prefer uvx, fall back to direct command
319
+ uvx_path = shutil.which("uvx")
320
+ direct_path = shutil.which("basecamp-mcp")
321
+
322
+ if uvx_path:
323
+ basecamp_server = {
324
+ "command": uvx_path,
325
+ "args": ["basecamp-mcp"],
326
+ }
327
+ elif direct_path:
328
+ basecamp_server = {
329
+ "command": direct_path,
330
+ "args": [],
331
+ }
332
+ else:
333
+ print(
334
+ "\nCould not find basecamp-mcp in PATH — skipping Claude Desktop auto-config."
335
+ )
336
+ return
337
+
338
+ # Read existing config or start fresh
339
+ if config_path.exists():
340
+ try:
341
+ existing = json.loads(config_path.read_text())
342
+ except (json.JSONDecodeError, OSError):
343
+ existing = {}
344
+ else:
345
+ config_path.parent.mkdir(parents=True, exist_ok=True)
346
+ existing = {}
347
+
348
+ if "mcpServers" not in existing:
349
+ existing["mcpServers"] = {}
350
+
351
+ existing["mcpServers"]["basecamp"] = basecamp_server
352
+ config_path.write_text(json.dumps(existing, indent=2) + "\n")
353
+ print(f"\nClaude Desktop config updated: {config_path}")