perplexity-web-mcp-cli 0.15.0__tar.gz → 0.16.1__tar.gz

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.
Files changed (48) hide show
  1. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/PKG-INFO +2 -2
  2. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/README.md +1 -1
  3. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/pyproject.toml +1 -1
  4. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/pyproject.toml.orig +1 -1
  5. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/cli/ai_doc.py +13 -4
  6. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/cli/main.py +74 -7
  7. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/cli/setup.py +8 -0
  8. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/core.py +128 -0
  9. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/data/SKILL.md +1 -1
  10. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/data/references/mcp-tools.md +5 -3
  11. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/mcp/server.py +48 -22
  12. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/shared.py +72 -6
  13. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/__init__.py +0 -0
  14. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/api/__init__.py +0 -0
  15. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/api/responses.py +0 -0
  16. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/api/server.py +0 -0
  17. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/api/session_manager.py +0 -0
  18. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/api/tool_calling.py +0 -0
  19. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/auth.py +0 -0
  20. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/catalog.py +0 -0
  21. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/cli/__init__.py +0 -0
  22. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/cli/auth.py +0 -0
  23. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/cli/doctor.py +0 -0
  24. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/cli/hack.py +0 -0
  25. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/cli/skill.py +0 -0
  26. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/config.py +0 -0
  27. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/connector_policy.py +0 -0
  28. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/constants.py +0 -0
  29. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/council.py +0 -0
  30. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/data/references/api-endpoints.md +0 -0
  31. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/data/references/models.md +0 -0
  32. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/enums.py +0 -0
  33. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/exceptions.py +0 -0
  34. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/http.py +0 -0
  35. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/limits.py +0 -0
  36. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/logging.py +0 -0
  37. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/mcp/__init__.py +0 -0
  38. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/mcp/__main__.py +0 -0
  39. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/models.py +0 -0
  40. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/preferences.py +0 -0
  41. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/py.typed +0 -0
  42. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/rate_limits.py +0 -0
  43. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/resilience.py +0 -0
  44. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/router.py +0 -0
  45. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/sessions.py +0 -0
  46. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/token_store.py +0 -0
  47. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/trace.py +0 -0
  48. {perplexity_web_mcp_cli-0.15.0 → perplexity_web_mcp_cli-0.16.1}/src/perplexity_web_mcp/types.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: perplexity-web-mcp-cli
3
- Version: 0.15.0
3
+ Version: 0.16.1
4
4
  Summary: CLI, MCP server, and Anthropic/OpenAI API-compatible interface for Perplexity AI.
5
5
  Keywords: perplexity,ai,mcp,anthropic,api,client
6
6
  Author: Jacob BD
@@ -249,7 +249,7 @@ pwm chat -m auto # quota-aware model routing
249
249
  pwm chat -m claude_sonnet --thinking # start with a specific model
250
250
  ```
251
251
 
252
- In-session commands: `/new` starts a fresh thread, `/model [NAME]` shows or switches the model, `/exit` (or `/quit`, or Ctrl-D) quits.
252
+ In-session commands: `/new` starts a fresh thread, `/model [NAME]` shows or switches the model, `/source [NAME]` switches the source focus (stays set), `/thinking [on|off]` toggles extended thinking (stays set), `/attach PATH` attaches a file to your next message only, and `/exit` (or `/quit`, or Ctrl-D) quits.
253
253
 
254
254
  ### Saved Defaults
255
255
 
@@ -211,7 +211,7 @@ pwm chat -m auto # quota-aware model routing
211
211
  pwm chat -m claude_sonnet --thinking # start with a specific model
212
212
  ```
213
213
 
214
- In-session commands: `/new` starts a fresh thread, `/model [NAME]` shows or switches the model, `/exit` (or `/quit`, or Ctrl-D) quits.
214
+ In-session commands: `/new` starts a fresh thread, `/model [NAME]` shows or switches the model, `/source [NAME]` switches the source focus (stays set), `/thinking [on|off]` toggles extended thinking (stays set), `/attach PATH` attaches a file to your next message only, and `/exit` (or `/quit`, or Ctrl-D) quits.
215
215
 
216
216
  ### Saved Defaults
217
217
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "perplexity-web-mcp-cli"
3
- version = "0.15.0"
3
+ version = "0.16.1"
4
4
  description = "CLI, MCP server, and Anthropic/OpenAI API-compatible interface for Perplexity AI."
5
5
  license = "MIT"
6
6
  readme = "README.md"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "perplexity-web-mcp-cli"
3
- version = "0.15.0"
3
+ version = "0.16.1"
4
4
 
5
5
  description = "CLI, MCP server, and Anthropic/OpenAI API-compatible interface for Perplexity AI."
6
6
  authors = [{ name = "Jacob BD" }]
@@ -89,7 +89,11 @@ CHAT (INTERACTIVE)
89
89
  pwm chat -m MODEL -t -s SOURCE Same options as pwm ask
90
90
  pwm chat -m auto Quota-aware routing (downgrades when quota is low)
91
91
  In-session commands: /new (new thread),
92
- /model [NAME] (show or switch model), /exit (quit)
92
+ /model [NAME] (show or switch model),
93
+ /source [NAME] (switch source, sticky),
94
+ /thinking [on|off] (toggle thinking, sticky),
95
+ /attach PATH (attach a file to the next message),
96
+ /exit (quit)
93
97
 
94
98
  SAVED DEFAULTS
95
99
  pwm config show Show saved default model, thinking, source
@@ -201,19 +205,24 @@ MCP TOOLS (pplx_* namespace)
201
205
  ================================================================================
202
206
 
203
207
  SMART QUERY (RECOMMENDED DEFAULT — use this for every query):
204
- pplx_smart_query(query, intent="quick", source_focus="web")
208
+ pplx_smart_query(query, intent="quick", source_focus=None, files=None)
205
209
  Quota-aware routing. Default to intent='quick' for most lookups (Sonar 2 first).
206
210
  Only escalate to 'standard', 'detailed', or 'research' when needed.
211
+ Omitted source_focus follows the saved default (pwm config), then web.
212
+ files: attach local PDFs/images (on Free tier may count as a Pro Search).
207
213
  See QUOTA-AWARE QUERYING section above for decision rules.
208
214
  Multi-turn: responses end with [Conversation ID: ...]; pass it back via conversation_id to continue.
209
215
 
210
216
  QUERY TOOLS (each call costs 1 Pro Search query unless noted):
211
- pplx_query(query, model="auto", thinking=False, source_focus="web")
217
+ pplx_query(query, model="auto", thinking=False, source_focus=None, files=None)
212
218
  Explicit model selection. 1 PRO SEARCH per call.
213
219
  Omitted model/thinking/source follow saved defaults (pwm config); explicit values win.
220
+ An unknown model returns an error with close-match suggestions (no silent fallback).
221
+ files: attach local PDFs/images (on Free tier may count as a Pro Search).
214
222
 
215
- pplx_ask(query, source_focus="web")
223
+ pplx_ask(query, source_focus=None)
216
224
  Auto-selects best model. 1 PRO SEARCH per call.
225
+ Omitted source_focus follows the saved default (pwm config), then web.
217
226
 
218
227
  pplx_council(query, source_focus="web", models="gpt56_terra,claude_sonnet,gemini_pro",
219
228
  synthesize=True, thinking=False, chairman="sonar")
@@ -166,7 +166,11 @@ def _resolve_prompt(query: str | None, prompt_file: str | None) -> str:
166
166
  )
167
167
  @click.option("--json", "json_output", is_flag=True, help="Output as JSON.")
168
168
  @click.option("--no-citations", is_flag=True, help="Suppress citation URLs.")
169
- @click.option("--intent", default="standard", help="Routing intent: quick, standard, detailed, research.")
169
+ @click.option(
170
+ "--intent",
171
+ default="standard",
172
+ help="Routing intent when -m auto: quick, standard, detailed, research (ignored with an explicit model).",
173
+ )
170
174
  def ask_cmd(query, model_name, thinking, source, prompt_file, files, json_output, no_citations, intent):
171
175
  """Ask a question using Perplexity AI.
172
176
 
@@ -206,6 +210,13 @@ def _cmd_ask_impl(query, model_name, thinking, source, json_output, no_citations
206
210
  )
207
211
  return 1
208
212
 
213
+ if intent != "standard":
214
+ print(
215
+ f"Note: --intent '{intent}' is ignored with an explicit model (-m {model_name}); "
216
+ "pass -m auto to route by intent.",
217
+ file=sys.stderr,
218
+ )
219
+
209
220
  model = resolve_model(model_name, thinking=thinking)
210
221
  result = ask(query, model, source, files=files or None)
211
222
 
@@ -273,9 +284,12 @@ def chat(model_name, thinking, source):
273
284
 
274
285
  \b
275
286
  In-session commands:
276
- /new start a new thread
277
- /model [NAME] show or switch the model ('auto' = quota-aware routing)
278
- /exit quit (/quit and Ctrl-D also work)
287
+ /new start a new thread
288
+ /model [NAME] show or switch the model ('auto' = quota-aware routing)
289
+ /source [NAME] show or switch the source focus (stays set)
290
+ /thinking [on|off] toggle extended thinking (stays set)
291
+ /attach PATH attach a file to your next message only
292
+ /exit quit (/quit and Ctrl-D also work)
279
293
  """
280
294
  raise SystemExit(_cmd_chat_impl(model_name, thinking, source))
281
295
 
@@ -308,8 +322,9 @@ def _cmd_chat_impl(model_name, thinking, source):
308
322
  return 1
309
323
 
310
324
  conversation_id = None
325
+ pending_files: list[str] = []
311
326
  prompt = "You: " if sys.stdin.isatty() else ""
312
- print(f"Chatting with {model_name}. Commands: /new (new thread), /model (switch model), /exit (quit).")
327
+ print(f"Chatting with {model_name}. Commands: /new, /model, /source, /thinking, /attach, /exit.")
313
328
  while True:
314
329
  try:
315
330
  line = input(prompt)
@@ -323,6 +338,7 @@ def _cmd_chat_impl(model_name, thinking, source):
323
338
  break
324
339
  if query == "/new":
325
340
  conversation_id = None
341
+ pending_files = []
326
342
  print("Started a new thread.")
327
343
  continue
328
344
  if query == "/model" or query.startswith("/model "):
@@ -348,17 +364,68 @@ def _cmd_chat_impl(model_name, thinking, source):
348
364
  else:
349
365
  print(f"Error: Unknown model '{candidate}'. Type /model to see available names.", file=sys.stderr)
350
366
  continue
367
+ if query == "/source" or query.startswith("/source "):
368
+ candidate = query[len("/source") :].strip()
369
+ if not candidate:
370
+ print(f"Current source: {source}")
371
+ print(f"Available: {', '.join(SOURCE_FOCUS_NAMES)}, or a connector source ID.")
372
+ elif _validate_source_for_cli(candidate):
373
+ source = candidate
374
+ print(f"Source set to {source}.")
375
+ continue
376
+ if query == "/thinking" or query.startswith("/thinking "):
377
+ arg = query[len("/thinking") :].strip().lower()
378
+ if arg in ("on", "true", "yes"):
379
+ thinking = True
380
+ elif arg in ("off", "false", "no"):
381
+ thinking = False
382
+ elif not arg:
383
+ thinking = not thinking
384
+ else:
385
+ print(f"Usage: /thinking [on|off] (currently {'on' if thinking else 'off'}).", file=sys.stderr)
386
+ continue
387
+ print(f"Thinking {'on' if thinking else 'off'}.")
388
+ if model_name == "auto":
389
+ print("Note: thinking applies to specific models; 'auto' routing ignores it.")
390
+ continue
391
+ if query == "/attach" or query.startswith("/attach "):
392
+ candidate = query[len("/attach") :].strip()
393
+ if not candidate:
394
+ if pending_files:
395
+ print(f"Attached for next message: {', '.join(pending_files)}")
396
+ else:
397
+ print("Usage: /attach PATH (attaches a file to your next message only).")
398
+ continue
399
+ if candidate == "clear":
400
+ pending_files = []
401
+ print("Cleared pending attachments.")
402
+ continue
403
+ attachment = Path(candidate).expanduser()
404
+ if not attachment.is_file():
405
+ print(f"Error: File not found: {candidate}", file=sys.stderr)
406
+ continue
407
+ pending_files.append(str(attachment))
408
+ print(f"Attached for next message: {', '.join(pending_files)}")
409
+ continue
351
410
  try:
411
+ turn_files = pending_files or None
352
412
  if model_name == "auto":
353
413
  from perplexity_web_mcp.shared import smart_ask
354
414
 
355
- smart_response = smart_ask(query, source_focus=source, conversation_id=conversation_id)
415
+ smart_response = smart_ask(
416
+ query, source_focus=source, conversation_id=conversation_id, files=turn_files
417
+ )
356
418
  conversation_id = smart_response.conversation_id
357
419
  print(smart_response.format_response())
358
420
  else:
359
421
  model = resolve_model(model_name, thinking=thinking)
360
- response, conversation_id = ask_turn(query, model, source, conversation_id)
422
+ response, conversation_id = ask_turn(query, model, source, conversation_id, files=turn_files)
361
423
  print(response)
424
+ pending_files = []
425
+ except (FileValidationError, FileUploadError) as error:
426
+ print(str(error), file=sys.stderr)
427
+ pending_files = []
428
+ continue
362
429
  except (AuthenticationError, RateLimitError) as error:
363
430
  print(str(error), file=sys.stderr)
364
431
  continue
@@ -612,6 +612,14 @@ def _is_already_configured(client_id: str) -> bool:
612
612
  """Check if MCP is already configured for a client."""
613
613
  try:
614
614
  if client_id == "claude-code":
615
+ # Fast path: read the user-scope config that `claude mcp add -s user`
616
+ # writes. Avoids a false negative when `claude mcp list` is slow and
617
+ # its 5s timeout is swallowed below, returning False for a server that
618
+ # is actually configured.
619
+ claude_config = _read_json_config(Path.home() / ".claude.json")
620
+ servers = claude_config.get("mcpServers", {})
621
+ if MCP_SERVER_KEY in servers or "perplexity-web-mcp" in servers:
622
+ return True
615
623
  claude_cmd = shutil.which("claude")
616
624
  if claude_cmd:
617
625
  result = subprocess.run(
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  from mimetypes import guess_type
6
6
  from os import PathLike
7
7
  from pathlib import Path
8
+ from time import sleep
8
9
  from typing import TYPE_CHECKING, Any
9
10
  from uuid import uuid4
10
11
 
@@ -86,6 +87,87 @@ def _blocks_to_answer_data(blocks: Any) -> dict[str, Any]:
86
87
  return answer_data
87
88
 
88
89
 
90
+ def _extract_final_sources(
91
+ thread_data: dict[str, Any], backend_uuid: str | None = None
92
+ ) -> list[SearchResultItem] | None:
93
+ """Return the ordered source list stored with a thread's final answer.
94
+
95
+ The stored FINAL step embeds the same ``web_results`` payload the answer
96
+ model was given, in the order its ``[n]`` citation markers refer to. This
97
+ is the authoritative numbering for citation footers on multi-step
98
+ searches, where block arrival order does not match the markers. Returns
99
+ ``None`` when the payload cannot provide it (unknown thread, malformed
100
+ data, or a thread stored before the final answer was persisted).
101
+ """
102
+ entries = thread_data.get("entries")
103
+ if not isinstance(entries, list):
104
+ return None
105
+
106
+ entry: dict[str, Any] | None = None
107
+ if backend_uuid:
108
+ for candidate in reversed(entries):
109
+ if isinstance(candidate, dict) and candidate.get("backend_uuid") == backend_uuid:
110
+ entry = candidate
111
+ break
112
+ if entry is None:
113
+ for candidate in reversed(entries):
114
+ if isinstance(candidate, dict):
115
+ entry = candidate
116
+ break
117
+ if entry is None:
118
+ return None
119
+
120
+ raw_steps = entry.get("text")
121
+ try:
122
+ steps = loads(raw_steps) if isinstance(raw_steps, str) else raw_steps
123
+ except JSONDecodeError:
124
+ return None
125
+ if not isinstance(steps, list):
126
+ return None
127
+
128
+ final_step = next(
129
+ (step for step in reversed(steps) if isinstance(step, dict) and step.get("step_type") == "FINAL"),
130
+ None,
131
+ )
132
+ if final_step is None:
133
+ return None
134
+
135
+ content = final_step.get("content")
136
+ raw_answer = content.get("answer") if isinstance(content, dict) else None
137
+ if isinstance(raw_answer, str):
138
+ try:
139
+ answer_data = loads(raw_answer)
140
+ except JSONDecodeError:
141
+ return None
142
+ elif isinstance(raw_answer, dict):
143
+ answer_data = raw_answer
144
+ else:
145
+ return None
146
+ if not isinstance(answer_data, dict):
147
+ return None
148
+
149
+ raw_results: list[Any] = []
150
+ web_results = answer_data.get("web_results")
151
+ if isinstance(web_results, list):
152
+ raw_results.extend(web_results)
153
+ extra_web_results = answer_data.get("extra_web_results")
154
+ if isinstance(extra_web_results, list):
155
+ raw_results.extend(extra_web_results)
156
+
157
+ results: list[SearchResultItem] = []
158
+ seen_urls: set[str] = set()
159
+ for item in raw_results:
160
+ if not isinstance(item, dict):
161
+ continue
162
+ url = item.get("url")
163
+ if not url or url in seen_urls:
164
+ continue
165
+ seen_urls.add(url)
166
+ results.append(SearchResultItem(title=item.get("name"), snippet=item.get("snippet"), url=url))
167
+
168
+ return results or None
169
+
170
+
89
171
  class Perplexity:
90
172
  """Web scraper for Perplexity AI conversations."""
91
173
 
@@ -281,6 +363,7 @@ class Conversation:
281
363
  "_search_results",
282
364
  "_stream_generator",
283
365
  "_title",
366
+ "_web_results_blocks",
284
367
  )
285
368
 
286
369
  def __init__(self, http: HTTPClient, config: ConversationConfig) -> None:
@@ -296,6 +379,7 @@ class Conversation:
296
379
  self._search_results: list[SearchResultItem] = []
297
380
  self._raw_data: dict[str, Any] = {}
298
381
  self._stream_generator: Generator[Response, None, None] | None = None
382
+ self._web_results_blocks = 0
299
383
 
300
384
  @property
301
385
  def answer(self) -> str | None:
@@ -419,6 +503,7 @@ class Conversation:
419
503
  self._search_results = []
420
504
  self._raw_data = {}
421
505
  self._stream_generator = None
506
+ self._web_results_blocks = 0
422
507
 
423
508
  def _validate_files(self, files: list[str | PathLike] | None) -> list[_FileInfo]:
424
509
  if not files:
@@ -647,6 +732,8 @@ class Conversation:
647
732
  if "text" not in data:
648
733
  answer_data = _blocks_to_answer_data(data.get("blocks"))
649
734
  if answer_data:
735
+ if answer_data.get("web_results"):
736
+ self._web_results_blocks += 1
650
737
  self._update_state(data.get("thread_title"), answer_data)
651
738
  return None
652
739
 
@@ -773,6 +860,45 @@ class Conversation:
773
860
  raw_data=self._raw_data,
774
861
  )
775
862
 
863
+ def _refresh_search_results_from_thread(self) -> bool:
864
+ """Align the citation list with the thread's stored FINAL order.
865
+
866
+ Multi-step searches stream several ``web_results`` blocks, and the
867
+ answer's ``[n]`` markers follow the merged, model-facing source list
868
+ stored with the final answer rather than block arrival order. Fetch
869
+ the finished thread once and adopt that order when available; keep
870
+ the accumulated stream order on any failure.
871
+ """
872
+ if self._web_results_blocks <= 1 or not self._backend_uuid:
873
+ return False
874
+
875
+ endpoint = (
876
+ f"{ENDPOINT_THREAD_DETAIL}/{self._backend_uuid}"
877
+ f"?version={API_VERSION}&source=default&limit=100&from_first=true"
878
+ )
879
+ for attempt in (0, 1):
880
+ try:
881
+ response = self._http.get(endpoint)
882
+ thread_data = loads(response.content)
883
+ if isinstance(thread_data, dict):
884
+ ordered = _extract_final_sources(thread_data, self._backend_uuid)
885
+ if ordered:
886
+ previous = len(self._search_results)
887
+ self._search_results = ordered
888
+ log_trace(
889
+ f"[STAGE 3 - CITATION ORDER REFRESH] stored order applied: "
890
+ f"{previous} -> {len(ordered)} sources"
891
+ )
892
+ return True
893
+ except Exception as error: # noqa: BLE001 - best-effort refresh keeps stream order
894
+ logger.debug(f"Citation order refresh failed: {error}")
895
+ log_trace(f"[STAGE 3 - CITATION ORDER REFRESH] attempt {attempt + 1} failed: {error!r}")
896
+ if attempt == 0:
897
+ sleep(1.0)
898
+
899
+ log_trace("[STAGE 3 - CITATION ORDER REFRESH] no stored order found; keeping stream order")
900
+ return False
901
+
776
902
  def _fetch_research_report(self) -> str | None:
777
903
  """Return the full Deep Research report markdown, or ``None``.
778
904
 
@@ -859,6 +985,7 @@ class Conversation:
859
985
  finally:
860
986
  gen.close()
861
987
 
988
+ self._refresh_search_results_from_thread()
862
989
  self._append_research_report()
863
990
 
864
991
  def _stream(self, payload: dict[str, Any]) -> Generator[Response, None, None]:
@@ -874,5 +1001,6 @@ class Conversation:
874
1001
  finally:
875
1002
  gen.close()
876
1003
 
1004
+ self._refresh_search_results_from_thread()
877
1005
  if self._append_research_report():
878
1006
  yield self._build_response()
@@ -2,7 +2,7 @@
2
2
  name: perplexity-web-mcp
3
3
  description: 'Search the web and query AI models via Perplexity AI using perplexity-web-mcp-cli. Supports CLI commands (pwm ask, pwm chat, pwm research, pwm config), MCP tools (pplx_*), and Anthropic/OpenAI-compatible API server. Use when the user mentions "perplexity", "pplx", "pwm", "web search with AI", "chat with Perplexity", "deep research", "search the internet", or wants to query premium models like GPT-6 Sol, GPT-5.6 Terra, Grok 4.7, Claude, Gemini, GLM, Kimi, or Nemotron through Perplexity''s web interface.'
4
4
  metadata:
5
- version: "0.15.0"
5
+ version: "0.16.1"
6
6
  author: "Jacob BD"
7
7
 
8
8
  ---
@@ -110,8 +110,9 @@ and only escalate when the query genuinely needs a premium model or Research.
110
110
  pplx_smart_query(
111
111
  query: str, # Required. The question to ask.
112
112
  intent: str = "standard", # quick (1 Pro, Sonar 2), standard (1 Pro), detailed (1 Pro), research (1 Research)
113
- source_focus: str = "web", # none, web, academic, social, finance, all, or connector ID from pplx_connectors()
113
+ source_focus: str = None, # none, web, academic, social, finance, all, or connector ID; omitted → saved default, then web
114
114
  conversation_id: str = None, # Optional. Pass ID from previous turn to persist context.
115
+ files: list[str] = None, # Optional. Local file paths to attach (PDF/image). On Free tier may count as a Pro Search.
115
116
  ) -> str
116
117
  ```
117
118
 
@@ -133,10 +134,11 @@ pplx_query(
133
134
  thinking: bool = False, # Enable extended thinking (where supported)
134
135
  source_focus: str = "web", # none, web, academic, social, finance, all, or connector ID from pplx_connectors()
135
136
  conversation_id: str = None, # Optional. Pass ID from previous turn to persist context.
137
+ files: list[str] = None, # Optional. Local file paths to attach (PDF/image). On Free tier may count as a Pro Search.
136
138
  ) -> str
137
139
  ```
138
140
 
139
- Omitted `model`, `thinking`, and `source_focus` fall back to saved defaults (set with `pwm config` on the CLI), then to auto/web/off. Explicit values always win.
141
+ Omitted `model`, `thinking`, and `source_focus` fall back to saved defaults (set with `pwm config` on the CLI), then to auto/web/off. Explicit values always win. An unknown `model` returns an error with close-match suggestions instead of silently picking a default.
140
142
 
141
143
  ### pplx_ask
142
144
 
@@ -146,7 +148,7 @@ For simple lookups, prefer `pplx_smart_query(intent='quick')` instead.
146
148
  ```
147
149
  pplx_ask(
148
150
  query: str, # Required. The question to ask.
149
- source_focus: str = "web", # none, web, academic, social, finance, all, or connector ID from pplx_connectors()
151
+ source_focus: str = None, # none, web, academic, social, finance, all, or connector ID; omitted → saved default, then web
150
152
  conversation_id: str = None, # Optional. Pass ID from previous turn to persist context.
151
153
  ) -> str
152
154
  ```
@@ -21,11 +21,13 @@ from perplexity_web_mcp.auth import (
21
21
  resolve_redirect_url,
22
22
  verify_totp,
23
23
  )
24
+ from perplexity_web_mcp.exceptions import FileUploadError, FileValidationError
24
25
  from perplexity_web_mcp.models import Models
25
26
  from perplexity_web_mcp.preferences import load_preferences
26
27
  from perplexity_web_mcp.shared import (
27
28
  COUNCIL_DEFAULT_MODELS_STR,
28
29
  ModelName,
30
+ ModelResolutionError,
29
31
  SourceFocusName,
30
32
  SourceResolutionError,
31
33
  ask,
@@ -100,6 +102,7 @@ def pplx_query(
100
102
  thinking: bool | None = None,
101
103
  source_focus: SourceFocusName | None = None,
102
104
  conversation_id: str | None = None,
105
+ files: list[str] | None = None,
103
106
  ) -> str:
104
107
  """Query Perplexity AI with explicit model selection. COSTS 1 PRO SEARCH QUERY per call.
105
108
 
@@ -112,12 +115,15 @@ def pplx_query(
112
115
  query: The question to ask
113
116
  model: Model to use - auto, sonar, deep_research, gpt56_terra, gpt56_sol, gpt6_sol, grok45,
114
117
  grok47, claude_sonnet, claude_opus, claude_opus55, gemini_pro, gemini38, nemotron,
115
- glm52, glm53, kimi_k26, kimi_k3 (any live catalog identifier is also accepted)
118
+ glm52, glm53, kimi_k26, kimi_k3 (any live catalog identifier is also accepted).
119
+ An unknown name returns an error with close-match suggestions.
116
120
  thinking: Enable extended thinking mode (available for gpt56_terra, gpt56_sol, gpt6_sol, grok45,
117
121
  grok47, claude_sonnet, claude_opus, claude_opus55, gemini38, kimi_k26; always on for
118
122
  gemini_pro, nemotron, glm52, glm53, and kimi_k3)
119
123
  source_focus: Source type - none (model only, no search), web, academic,
120
124
  social, finance, all, or connector source ID from pplx_connectors()
125
+ files: Local file paths to attach (PDF or image). On Free-tier accounts an
126
+ attachment can make the query count as a Pro Search.
121
127
  """
122
128
  prefs = load_preferences()
123
129
  if model is None:
@@ -127,13 +133,21 @@ def pplx_query(
127
133
  if source_focus is None:
128
134
  source_focus = prefs.get("source") or "web"
129
135
 
130
- selected_model = resolve_model(model, thinking=thinking)
131
- return ask(query, selected_model, source_focus, conversation_id)
136
+ try:
137
+ selected_model = resolve_model(model, thinking=thinking)
138
+ return ask(query, selected_model, source_focus, conversation_id, files=files)
139
+ except (ModelResolutionError, FileValidationError, FileUploadError) as error:
140
+ return str(error)
132
141
 
133
142
 
134
143
  @mcp.tool
135
- def pplx_ask(query: str, source_focus: SourceFocusName = "web", conversation_id: str | None = None) -> str:
136
- """Quick Q&A with auto model. COSTS 1 PRO SEARCH QUERY. Prefer pplx_smart_query(intent='quick') for simple lookups (Sonar 2 first)."""
144
+ def pplx_ask(query: str, source_focus: SourceFocusName | None = None, conversation_id: str | None = None) -> str:
145
+ """Quick Q&A with auto model. COSTS 1 PRO SEARCH QUERY. Prefer pplx_smart_query(intent='quick') for simple lookups (Sonar 2 first).
146
+
147
+ An omitted source_focus falls back to your saved default (set with `pwm config`), then web.
148
+ """
149
+ if source_focus is None:
150
+ source_focus = load_preferences().get("source") or "web"
137
151
  return ask(query, Models.BEST, source_focus, conversation_id)
138
152
 
139
153
 
@@ -320,8 +334,9 @@ def pplx_kimi_k26_thinking(
320
334
  def pplx_smart_query(
321
335
  query: str,
322
336
  intent: str = "standard",
323
- source_focus: SourceFocusName = "web",
337
+ source_focus: SourceFocusName | None = None,
324
338
  conversation_id: str | None = None,
339
+ files: list[str] | None = None,
325
340
  ) -> str:
326
341
  """RECOMMENDED DEFAULT TOOL. Quota-aware query — checks limits and picks the best model automatically.
327
342
 
@@ -342,10 +357,20 @@ def pplx_smart_query(
342
357
  query: The question to ask
343
358
  intent: Query complexity — quick (default for most), standard, detailed, research
344
359
  source_focus: Source type — none (model only, no search), web, academic,
345
- social, finance, all, or connector source ID from pplx_connectors()
360
+ social, finance, all, or connector source ID from pplx_connectors().
361
+ Omit it to use your saved default (set with `pwm config`), then web.
346
362
  conversation_id: Pass the ID from a previous response to continue that thread
363
+ files: Local file paths to attach (PDF or image). On Free-tier accounts an
364
+ attachment can make the query count as a Pro Search.
347
365
  """
348
- result = smart_ask(query, intent=intent, source_focus=source_focus, conversation_id=conversation_id)
366
+ if source_focus is None:
367
+ source_focus = load_preferences().get("source") or "web"
368
+ try:
369
+ result = smart_ask(
370
+ query, intent=intent, source_focus=source_focus, conversation_id=conversation_id, files=files
371
+ )
372
+ except (FileValidationError, FileUploadError) as error:
373
+ return str(error)
349
374
  return result.format_response()
350
375
 
351
376
 
@@ -361,8 +386,8 @@ def pplx_council(
361
386
  """Model Council — query multiple models in parallel, get synthesized consensus.
362
387
 
363
388
  IMPORTANT — BEFORE calling this tool, you MUST:
364
- 1. Tell the user the available models: sonar, gpt56_terra, gpt56_sol, grok45, claude_sonnet, claude_opus, gemini_pro, nemotron, glm52, kimi_k26
365
- 2. Check pplx_usage() first. If Subscription is Pro, do not include Max-only models: gpt56_sol, claude_opus
389
+ 1. Tell the user the available models: sonar, gpt56_terra, gpt56_sol, gpt6_sol, grok45, grok47, claude_sonnet, claude_opus, claude_opus55, gemini_pro, gemini38, nemotron, glm52, glm53, kimi_k26, kimi_k3
390
+ 2. Check pplx_usage() first. If Subscription is Pro, do not include Max-only models: gpt56_sol, claude_opus, claude_opus55
366
391
  3. Ask the user WHICH models they want in their council and HOW MANY
367
392
  4. Inform them of the cost: each council model = 1 Pro Search query, plus synthesis
368
393
  (default chairman sonar = Sonar 2 pass — still counts as a normal query toward limits)
@@ -374,25 +399,26 @@ def pplx_council(
374
399
  query: The question to ask all council models
375
400
  source_focus: Source type for all models (none/web/academic/social/finance/all or connector source ID)
376
401
  models: Comma-separated model names to use as council members.
377
- Available: sonar, gpt56_terra, gpt56_sol, grok45, claude_sonnet, claude_opus, gemini_pro, nemotron, glm52, kimi_k26.
402
+ Available: sonar, gpt56_terra, gpt56_sol, gpt6_sol, grok45, grok47, claude_sonnet, claude_opus, claude_opus55, gemini_pro, gemini38, nemotron, glm52, glm53, kimi_k26, kimi_k3.
378
403
  Default: "gpt56_terra,claude_sonnet,gemini_pro" (3 models + synthesis = 4 Pro Searches)
379
- Max-only: gpt56_sol, claude_opus. Exclude these when pplx_usage shows a Pro subscription.
404
+ Max-only: gpt56_sol, claude_opus, claude_opus55. Exclude these when pplx_usage shows a Pro subscription.
380
405
  synthesize: Whether to synthesize a consensus from all responses.
381
406
  Set false to get only individual responses (saves 1 Sonar 2 call).
382
- thinking: Enable extended thinking for council models (gpt56_terra, gpt56_sol, grok45, claude_sonnet,
383
- claude_opus, kimi_k26 support toggle; gemini_pro, nemotron, and glm52 are always thinking).
407
+ thinking: Enable extended thinking for council models (gpt56_terra, gpt56_sol, gpt6_sol, grok45, grok47,
408
+ claude_sonnet, claude_opus, claude_opus55, gemini38, kimi_k26 support toggle; gemini_pro,
409
+ nemotron, glm52, and glm53 are always thinking).
384
410
  chairman: Model to use for synthesis (default: "sonar" / Sonar 2).
385
411
  Non-sonar chairmen cost 1 extra Pro Search query.
386
412
  """
387
- # Parse custom model list if provided
388
- model_list = None
389
- if models != COUNCIL_DEFAULT_MODELS_STR:
390
- model_names = [name.strip() for name in models.split(",") if name.strip()]
391
- model_list = build_council_model_list(model_names, thinking=thinking)
413
+ try:
414
+ # Parse custom model list if provided
415
+ model_list = None
416
+ if models != COUNCIL_DEFAULT_MODELS_STR:
417
+ model_names = [name.strip() for name in models.split(",") if name.strip()]
418
+ model_list = build_council_model_list(model_names, thinking=thinking)
392
419
 
393
- synthesis_model = resolve_model(chairman) if chairman != "sonar" else None
420
+ synthesis_model = resolve_model(chairman) if chairman != "sonar" else None
394
421
 
395
- try:
396
422
  result = council_ask(
397
423
  query=query,
398
424
  models=model_list,
@@ -401,7 +427,7 @@ def pplx_council(
401
427
  thinking=thinking,
402
428
  synthesis_model=synthesis_model,
403
429
  )
404
- except SourceResolutionError as e:
430
+ except (ModelResolutionError, SourceResolutionError) as e:
405
431
  return str(e)
406
432
  return result.format_response()
407
433
 
@@ -8,9 +8,11 @@ Both the MCP server (mcp/server.py) and CLI (cli/main.py) import from here.
8
8
  from __future__ import annotations
9
9
 
10
10
  from dataclasses import dataclass
11
+ import difflib
11
12
  from os import PathLike, environ
12
13
  import re
13
14
  from threading import Lock
15
+ from time import monotonic
14
16
  from typing import TYPE_CHECKING, Literal
15
17
  from uuid import uuid4
16
18
 
@@ -74,6 +76,10 @@ class SourceResolutionError(ValueError):
74
76
  """Raised when a source alias or connector source ID cannot be resolved."""
75
77
 
76
78
 
79
+ class ModelResolutionError(ValueError):
80
+ """Raised when a model name cannot be resolved to a known or live-catalog model."""
81
+
82
+
77
83
  MODEL_METADATA: dict[str, ModelDefinition] = {
78
84
  "auto": ModelDefinition(Models.AUTO, None, "Auto (Concise)", "Perplexity", council_eligible=False),
79
85
  "sonar": ModelDefinition(Models.SONAR, None, "Sonar 2", "Perplexity"),
@@ -246,11 +252,59 @@ def build_council_model_list(
246
252
  return model_list
247
253
 
248
254
 
255
+ _catalog_refresh_lock = Lock()
256
+ _catalog_refreshed = False
257
+ _catalog_fetch_failed_at: float = 0.0
258
+ _CATALOG_FETCH_COOLDOWN_SECONDS = 60.0
259
+
260
+
261
+ def _lazy_refresh_catalog() -> bool:
262
+ """Fetch the live catalog once per process when a model name is unknown.
263
+
264
+ Returns True when a fresh catalog is cached and worth re-checking, False when
265
+ the fetch was skipped (recent-failure cooldown) or failed (offline/auth). A
266
+ failure is remembered so repeated unknown-name lookups do not hammer the
267
+ network while offline.
268
+ """
269
+ global _catalog_refreshed, _catalog_fetch_failed_at # noqa: PLW0603
270
+
271
+ with _catalog_refresh_lock:
272
+ if _catalog_refreshed:
273
+ return True
274
+ if _catalog_fetch_failed_at and (monotonic() - _catalog_fetch_failed_at) < _CATALOG_FETCH_COOLDOWN_SECONDS:
275
+ return False
276
+
277
+ from .catalog import fetch_catalog, save_catalog
278
+
279
+ try:
280
+ entries = fetch_catalog()
281
+ except Exception: # noqa: BLE001 - offline/auth/parse failures must degrade gracefully
282
+ _catalog_fetch_failed_at = monotonic()
283
+ return False
284
+
285
+ save_catalog(entries)
286
+ _catalog_refreshed = True
287
+ return True
288
+
289
+
290
+ def _unknown_model_message(name: str) -> str:
291
+ """Build a strict-resolution error naming close matches for an unknown model."""
292
+ suggestions = difflib.get_close_matches(name, known_model_names(), n=3, cutoff=0.6)
293
+ hint = f" Did you mean: {', '.join(suggestions)}?" if suggestions else ""
294
+ return (
295
+ f"Unknown model '{name}'.{hint} "
296
+ f"Run 'pwm models' to list available models, or use one of: {', '.join(MODEL_NAMES)}."
297
+ )
298
+
299
+
249
300
  def resolve_model(name: str, thinking: bool = False) -> Model:
250
301
  """Resolve a model name string to a Model instance.
251
302
 
252
- Falls back to the cached live catalog for identifiers newer than the static
253
- map, and finally to Models.BEST for unknown names.
303
+ Resolution order: the static catalog, then the cached live catalog, then a
304
+ single lazy live fetch. When the fetch succeeds and the name is still
305
+ unknown, a ModelResolutionError is raised with close-match suggestions
306
+ instead of silently guessing. When the fetch fails (offline), resolution
307
+ degrades to Models.BEST so a valid-but-uncached name is never rejected.
254
308
 
255
309
  Args:
256
310
  name: Model name key (e.g. "gpt56_terra", "claude_sonnet") or a live
@@ -259,15 +313,27 @@ def resolve_model(name: str, thinking: bool = False) -> Model:
259
313
 
260
314
  Returns:
261
315
  The resolved Model.
316
+
317
+ Raises:
318
+ ModelResolutionError: When the name is unknown and the live catalog was
319
+ fetched successfully (so the name is authoritatively invalid).
262
320
  """
263
321
  model_tuple = MODEL_MAP.get(name)
264
- if model_tuple is None:
322
+ if model_tuple is not None:
323
+ base_model, thinking_model = model_tuple
324
+ return thinking_model if thinking and thinking_model else base_model
325
+
326
+ live_model = cached_live_model(name, thinking=thinking)
327
+ if live_model is not None:
328
+ return live_model
329
+
330
+ if _lazy_refresh_catalog():
265
331
  live_model = cached_live_model(name, thinking=thinking)
266
332
  if live_model is not None:
267
333
  return live_model
268
- model_tuple = (Models.BEST, None)
269
- base_model, thinking_model = model_tuple
270
- return thinking_model if thinking and thinking_model else base_model
334
+ raise ModelResolutionError(_unknown_model_message(name))
335
+
336
+ return Models.BEST
271
337
 
272
338
 
273
339
  def _source_limits_from_rate_limits() -> list[SourceLimit]: