-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1954 lines (1768 loc) · 79.6 KB
/
server.py
File metadata and controls
1954 lines (1768 loc) · 79.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Dev.to MCP Server - A server implementation for interacting with Dev.to API
This program provides an MCP server interface to the Dev.to API.
Copyright (C) 2023 <Your Name/Organization>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import os
import json
import logging
import asyncio
from typing import List, Dict, Any, Optional, Union, Annotated, Iterator
from dotenv import load_dotenv
from datetime import datetime
import threading
import re
# Load environment variables from .env file
load_dotenv()
import httpx
from fastapi import FastAPI, Request, Response, Query, Body, Path, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from fastmcp import FastMCP, Context
from pydantic import BaseModel, Field
# Load configuration from environment variables
PORT = int(os.environ.get("PORT", 8080))
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
REST_PORT = int(os.environ.get("REST_PORT", 8001))
# Configure logging based on environment variable
logging.basicConfig(
level=getattr(logging, LOG_LEVEL, logging.INFO),
format="%(asctime)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger("devto-mcp")
# Log configuration (without sensitive data)
logger.info(f"Starting server with PORT={PORT}, LOG_LEVEL={LOG_LEVEL}, REST_PORT={REST_PORT}")
# Constants
DEVTO_API_BASE_URL = "https://dev.to/api"
# API client for Dev.to interactions
class DevToClient:
"""Client for interacting with the Dev.to API."""
def __init__(self, api_key: str = None):
"""Initialize the Dev.to API client."""
self.base_url = DEVTO_API_BASE_URL
self.api_key = api_key
async def _get_headers(self) -> Dict[str, str]:
"""Get headers for API requests."""
headers = {"Accept": "application/json", "Content-Type": "application/json"}
if self.api_key:
headers["api-key"] = self.api_key
return headers
async def get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Any:
"""Make a GET request to the Dev.to API."""
async with httpx.AsyncClient() as client:
headers = await self._get_headers()
url = f"{self.base_url}{path}"
response = await client.get(url, params=params, headers=headers, timeout=10.0)
response.raise_for_status()
return response.json()
async def post(self, path: str, data: Dict[str, Any]) -> Any:
"""Make a POST request to the Dev.to API."""
if not self.api_key:
raise ValueError("Dev.to API key is required for POST operations")
async with httpx.AsyncClient() as client:
headers = await self._get_headers()
url = f"{self.base_url}{path}"
response = await client.post(url, json=data, headers=headers, timeout=10.0)
response.raise_for_status()
return response.json()
async def put(self, path: str, data: Dict[str, Any]) -> Any:
"""Make a PUT request to the Dev.to API."""
if not self.api_key:
raise ValueError("Dev.to API key is required for PUT operations")
async with httpx.AsyncClient() as client:
headers = await self._get_headers()
url = f"{self.base_url}{path}"
response = await client.put(url, json=data, headers=headers, timeout=10.0)
response.raise_for_status()
return response.json()
# Custom exception for MCP-related errors
class MCPError(Exception):
"""Custom exception for MCP-related errors."""
def __init__(self, message: str, status_code: int = 400):
self.message = message
self.status_code = status_code
super().__init__(self.message)
# Create FastAPI app for health checks and info endpoints
app = FastAPI(
title="Dev.to MCP Server",
description="An MCP server for interacting with the Dev.to API",
version="1.0.0",
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Create MCP server
mcp = FastMCP(
name="Dev.to API",
description="MCP server for interacting with the Dev.to API",
instructions="""
# Dev.to API MCP Server
This server provides tools for interacting with the Dev.to API,
allowing you to browse, search, read, and create content.
## Required Configuration
This MCP server requires a Dev.to API key to function properly.
Please provide your Dev.to API key in the server environment:
```bash
export DEVTO_API_KEY="your_dev_to_api_key_here"
```
## Available Tools
### Browsing Content
- browse_latest_articles(): Get recent articles from Dev.to
- browse_popular_articles(): Get popular articles
- browse_articles_by_tag(tag): Get articles with a specific tag
- browse_articles_by_title(title): Get articles with a specific title
### Reading Content
- get_article(id): Get article details by ID
- get_article_by_title(title): Get article details by title
- get_user_profile(username): Get information about a Dev.to user
- get_article_by_id(id): Get article details by ID
- analyze_article(id): Analyze a specific article
- analyze_user_profile(username): Analyze a specific user profile
### Searching Content
- search_articles(query, page): Search for articles by keywords
### Managing Content
- list_my_articles(page, per_page): List your published articles
- list_my_draft_articles(page, per_page): List your draft articles
- list_my_unpublished_articles(page, per_page): List your unpublished articles
- list_my_scheduled_articles(page, per_page): List your scheduled articles
- create_article(title, content, tags, published): Create a new article
- update_article(id, title, content, tags, published): Update an existing article
- delete_article(id): Delete an existing article
- publish_article(id): Publish an existing article
- publish_article_by_title(title): Publish an existing article by title
- unpublish_article(id): Unpublish an existing article
- unpublish_article_by_title(title): Unpublish an existing article by title
## Examples
- To find Python articles: search_articles("python")
- To get an article: get_article(12345)
- To get an article by title: get_article_by_title("Title")
- To create an article: create_article("Title", "Content", "tag1,tag2", false)
- To update an article: update_article(12345, "Title", "Content", "tag1,tag2", false)
- To see your articles: list_my_articles()
- To see your draft articles: list_my_draft_articles()
- To see your unpublished articles: list_my_unpublished_articles()
- To see your scheduled articles: list_my_scheduled_articles()
- To delete an article: delete_article(12345)
- To publish an article: publish_article(12345)
- To publish an article by title: publish_article_by_title("Title")
- To unpublish an article: unpublish_article(12345)
- To unpublish an article by title: unpublish_article_by_title("Title")
- To get user profile: get_user_profile("username")
- To search articles: search_articles("query")
"""
)
# Import prompts from the new modules
from prompts.article_prompts import (
get_article_prompt,
get_article_by_title_prompt,
list_my_articles_prompt,
list_my_draft_articles_prompt,
list_my_unpublished_articles_prompt,
list_my_scheduled_articles_prompt,
create_article_prompt,
update_article_prompt,
update_article_by_title_prompt,
delete_article_prompt,
get_article_by_id_prompt,
search_articles_prompt,
publish_article_prompt,
publish_article_by_title_prompt,
unpublish_article_prompt,
unpublish_article_by_title_prompt,
analyze_article
)
from prompts.user_prompts import (
get_user_profile_prompt,
analyze_user_profile,
analyze_user_profile_by_id
)
# Register prompts with MCP server
get_article_prompt = mcp.prompt()(get_article_prompt)
get_article_by_title_prompt = mcp.prompt()(get_article_by_title_prompt)
list_my_articles_prompt = mcp.prompt()(list_my_articles_prompt)
list_my_draft_articles_prompt = mcp.prompt()(list_my_draft_articles_prompt)
list_my_unpublished_articles_prompt = mcp.prompt()(list_my_unpublished_articles_prompt)
list_my_scheduled_articles_prompt = mcp.prompt()(list_my_scheduled_articles_prompt)
create_article_prompt = mcp.prompt()(create_article_prompt)
update_article_prompt = mcp.prompt()(update_article_prompt)
update_article_by_title_prompt = mcp.prompt()(update_article_by_title_prompt)
delete_article_prompt = mcp.prompt()(delete_article_prompt)
get_article_by_id_prompt = mcp.prompt()(get_article_by_id_prompt)
search_articles_prompt = mcp.prompt()(search_articles_prompt)
analyze_article = mcp.prompt()(analyze_article)
get_user_profile_prompt = mcp.prompt()(get_user_profile_prompt)
analyze_user_profile = mcp.prompt()(analyze_user_profile)
analyze_user_profile_by_id = mcp.prompt()(analyze_user_profile_by_id)
publish_article_prompt = mcp.prompt()(publish_article_prompt)
publish_article_by_title_prompt = mcp.prompt()(publish_article_by_title_prompt)
unpublish_article_prompt = mcp.prompt()(unpublish_article_prompt)
unpublish_article_by_title_prompt = mcp.prompt()(unpublish_article_by_title_prompt)
# Helper functions for formatting responses
def format_article_list(articles: List[Dict[str, Any]]) -> str:
"""Format a list of articles for display."""
if not articles:
return "No articles found."
result = []
result.append("# Articles")
result.append("")
for article in articles:
title = article.get("title", "Untitled")
id = article.get("id", "Unknown ID")
username = article.get("user", {}).get("username", "unknown")
date = article.get("published_at", "Unknown date")
tags = article.get("tag_list", [])
tags_str = ", ".join(tags) if isinstance(tags, list) else tags
result.append(f"## {title}")
result.append(f"ID: {id}")
result.append(f"Author: {username}")
result.append(f"Published: {date}")
result.append(f"Tags: {tags_str}")
result.append(f"URL: {article.get('url', '')}")
result.append("")
result.append(article.get("description", "No description available."))
result.append("")
return "\n".join(result)
def ensure_list(val):
if isinstance(val, list):
return val
if isinstance(val, str):
return [t.strip() for t in val.split(",") if t.strip()]
return []
def format_article_detail(article: Dict[str, Any]) -> Dict[str, Any]:
return {
"id": article.get("id"),
"title": article.get("title", "Untitled"),
"url": article.get("url", ""),
"published_at": article.get("published_at"),
"description": article.get("description"),
"tags": ensure_list(article.get("tag_list", article.get("tags", []))),
"author": article.get("user", {}).get("username", "unknown"),
"published": bool(article.get("published", False)),
"body_markdown": article.get("body_markdown"),
"body_html": article.get("body_html"),
"content": article.get("body_markdown") or article.get("body_html") or "",
}
async def find_all_my_articles(api_key: str = None) -> List[Dict[str, Any]]:
"""
Retrieve all articles (published, drafts, scheduled) belonging to the authenticated user.
"""
if not api_key:
logger.error("Missing API key for find_all_my_articles")
raise MCPError("API key is required for this operation. Please provide a Dev.to API key in your server environment.", 401)
try:
client = DevToClient(api_key=api_key)
articles = await client.get("/articles/me/all")
return articles
except Exception as e:
logger.error(f"Error finding all my articles: {str(e)}")
raise MCPError(f"Failed to find all my articles: {str(e)}")
def format_article_list(articles: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Format a list of articles."""
if not articles:
return []
return [{
"id": article.get("id", "Unknown ID"),
"title": article.get("title", "Untitled"),
"url": article.get("url", ""),
"published_at": article.get("published_at", "Unknown date"),
"description": article.get("description", ""),
"tags": article.get("tag_list", []),
"author": article.get("user", {}).get("username", "unknown")
} for article in articles]
def format_user_profile(user: Dict[str, Any]) -> Dict[str, Any]:
"""Format user profile information."""
if not user:
return {"error": "User not found."}
return {
"name": user.get("name", "Unknown"),
"username": user.get("username", "unknown"),
"bio": user.get("summary", "No bio available."),
"location": user.get("location", ""),
"joined_at": user.get("joined_at", ""),
"twitter_username": user.get("twitter_username", ""),
"github_username": user.get("github_username", ""),
"website_url": user.get("website_url", "")
}
# Helper function to get API key from server environment
def get_api_key(request: Request = None) -> str:
"""Get the API key from server environment."""
mode = os.environ.get("SERVER_MODE", "sse").lower()
if mode == "rest":
if request is None:
return None
auth_header = request.headers.get("Authorization", "")
if auth_header.startswith("Bearer "):
return auth_header[7:].strip()
return None
else:
return os.environ.get('DEVTO_API_KEY')
# Helper class for returning structured data directly (without using MCPResponse)
class ArticleListResponse:
"""Helper to format article data as structured content."""
@staticmethod
def create(articles: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Create a properly structured response with the articles as direct content."""
# Return the articles directly as a list - FastMCP will handle the proper serialization
return articles
# Function to convert raw articles to a simplified list with essential details
def simplify_articles(articles: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Convert raw article data to a simplified list with essential details."""
def get_published(article):
# If 'published' is missing, treat as False (unpublished)
if "published" not in article:
return False
# If present but None, treat as False
return bool(article.get("published", False))
return [
{
"id": article.get("id"),
"title": article.get("title"),
"url": article.get("url"),
"published_at": article.get("published_at"),
"description": article.get("description"),
"tags": ensure_list(article.get("tag_list", article.get("tags", []))),
"author": article.get("user", {}).get("username") if article.get("user") else None,
"published": get_published(article)
}
for article in articles
]
# Pydantic models
class ArticleResponse(BaseModel):
id: int
title: str
url: str
published_at: Optional[str]
description: str
tags: List[str]
author: str
published: bool
class ScheduledArticleResponse(BaseModel):
id: int
title: str
url: str
published_at: Optional[str]
description: str
tags: List[str]
author: str
scheduled: bool = Field(..., description="True if the article is scheduled for future publication.")
published: bool
class ArticleDetailResponse(BaseModel):
id: int
title: str
url: str
published_at: Optional[str]
description: Optional[str]
tags: List[str]
author: str
published: bool
body_markdown: Optional[str]
body_html: Optional[str]
content: Optional[str]
# MCP Tool implementations
@mcp.tool()
async def browse_latest_articles(
page: Annotated[int, Field(description="Starting page number for pagination")] = 1,
per_page: Annotated[int, Field(description="Number of articles per page")] = 30,
max_pages: Annotated[int, Field(description="Maximum number of pages to search")] = 10,
ctx: Context = None
) -> List[Dict[str, Any]]:
"""
Get the most recent articles from Dev.to across multiple pages.
This tool will fetch recent articles from Dev.to, looking through multiple
pages until it reaches the maximum page limit.
"""
try:
# Create a client with the API key from server environment
client = DevToClient(api_key=get_api_key())
# Track all articles across multiple pages
all_articles = []
current_page = page
max_page_to_search = page + max_pages - 1
# Report initial progress
if ctx:
await ctx.report_progress(progress=10, total=100)
# Search through pages until we reach the limit or run out of results
while current_page <= max_page_to_search:
try:
# Fetch articles for the current page
articles = await client.get("/articles/latest", params={
"page": current_page,
"per_page": per_page
})
# If we received no articles, we've reached the end
if not articles or len(articles) == 0:
break
# Add articles to our collection
all_articles.extend(articles)
# Update progress periodically
if ctx:
progress = min(90, int(10 + (current_page - page) / max_pages * 80))
await ctx.report_progress(progress=progress, total=100)
# Move to the next page
current_page += 1
except Exception as e:
logger.warning(f"Error fetching latest articles page {current_page}: {str(e)}")
# Continue to the next page even if there's an error
current_page += 1
# Complete progress
if ctx:
await ctx.report_progress(progress=100, total=100)
# Return a simplified list of articles with essential details
simplified_articles = simplify_articles(all_articles)
return ArticleListResponse.create(simplified_articles)
except Exception as e:
logger.error(f"Error getting latest articles: {str(e)}")
raise MCPError(f"Failed to get latest articles: {str(e)}")
@mcp.tool()
async def browse_popular_articles(
page: Annotated[int, Field(description="Starting page number for pagination")] = 1,
per_page: Annotated[int, Field(description="Number of articles per page")] = 30,
max_pages: Annotated[int, Field(description="Maximum number of pages to search")] = 10,
ctx: Context = None
) -> List[Dict[str, Any]]:
"""
Get the most popular articles from Dev.to across multiple pages.
This tool will fetch popular articles from Dev.to, looking through multiple
pages until it reaches the maximum page limit.
"""
try:
# Create a client with the API key from server environment
client = DevToClient(api_key=get_api_key())
# Track all articles across multiple pages
all_articles = []
current_page = page
max_page_to_search = page + max_pages - 1
# Report initial progress
if ctx:
await ctx.report_progress(progress=10, total=100)
# Search through pages until we reach the limit or run out of results
while current_page <= max_page_to_search:
try:
# Fetch articles for the current page
articles = await client.get("/articles", params={
"page": current_page,
"per_page": per_page
})
# If we received no articles, we've reached the end
if not articles or len(articles) == 0:
break
# Add articles to our collection
all_articles.extend(articles)
# Update progress periodically
if ctx:
progress = min(90, int(10 + (current_page - page) / max_pages * 80))
await ctx.report_progress(progress=progress, total=100)
# Move to the next page
current_page += 1
except Exception as e:
logger.warning(f"Error fetching popular articles page {current_page}: {str(e)}")
# Continue to the next page even if there's an error
current_page += 1
# Complete progress
if ctx:
await ctx.report_progress(progress=100, total=100)
# Return a simplified list of articles with essential details
simplified_articles = simplify_articles(all_articles)
return ArticleListResponse.create(simplified_articles)
except Exception as e:
logger.error(f"Error getting popular articles: {str(e)}")
raise MCPError(f"Failed to get popular articles: {str(e)}")
@mcp.tool()
async def browse_articles_by_tag(
tag: Annotated[str, Field(description="The tag to filter articles by")],
page: Annotated[int, Field(description="Starting page number for pagination")] = 1,
per_page: Annotated[int, Field(description="Number of articles per page")] = 30,
max_pages: Annotated[int, Field(description="Maximum number of pages to search")] = 10,
ctx: Context = None
) -> List[Dict[str, Any]]:
"""
Get articles with a specific tag across multiple pages.
This tool will fetch articles with the specified tag from Dev.to, looking through multiple
pages until it reaches the maximum page limit.
"""
try:
# Create a client with the API key from server environment
client = DevToClient(api_key=get_api_key())
# Track all articles across multiple pages
all_articles = []
current_page = page
max_page_to_search = page + max_pages - 1
# Report initial progress
if ctx:
await ctx.report_progress(progress=10, total=100)
# Search through pages until we reach the limit or run out of results
while current_page <= max_page_to_search:
try:
# Fetch articles for the current page
articles = await client.get("/articles", params={
"tag": tag,
"page": current_page,
"per_page": per_page
})
# If we received no articles, we've reached the end
if not articles or len(articles) == 0:
break
# Add articles to our collection
all_articles.extend(articles)
# Update progress periodically
if ctx:
progress = min(90, int(10 + (current_page - page) / max_pages * 80))
await ctx.report_progress(progress=progress, total=100)
# Move to the next page
current_page += 1
except Exception as e:
logger.warning(f"Error fetching articles with tag '{tag}' on page {current_page}: {str(e)}")
# Continue to the next page even if there's an error
current_page += 1
# Complete progress
if ctx:
await ctx.report_progress(progress=100, total=100)
# Return a simplified list of articles with essential details
simplified_articles = simplify_articles(all_articles)
return ArticleListResponse.create(simplified_articles)
except Exception as e:
logger.error(f"Error getting articles by tag: {str(e)}")
raise MCPError(f"Failed to get articles with tag '{tag}': {str(e)}")
@mcp.tool()
async def get_article(
id: Annotated[str, Field(description="The ID of the article to retrieve")],
ctx: Context = None
) -> Dict[str, Any]:
"""
Get a specific article by ID.
"""
try:
client = DevToClient(api_key=get_api_key())
# 1. Try public endpoint first
try:
article = await client.get(f"/articles/{id}")
return format_article_detail(article)
except httpx.HTTPStatusError as e:
if e.response.status_code != 404:
return {"error": f"HTTP error: {e.response.status_code} - {e.response.text}"}
# 2. Fallback: search /articles/me/all for unpublished articles only
page = 1
per_page = 30
max_pages = 10
while page <= max_pages:
articles = await client.get("/articles/me/all", params={"page": page, "per_page": per_page})
for article in articles:
if article.get("published"):
# Stop searching—published articles are accessible via public endpoint
return {"error": f"Article not found with ID: {id}"}
if str(article.get("id")) == str(id):
return format_article_detail(article)
if not articles or len(articles) == 0:
break
page += 1
return {"error": f"Article not found with ID: {id}"}
except Exception as e:
return {"error": str(e)}
@mcp.tool()
async def get_article_by_title(
title: Annotated[str, Field(description="The title of the article")],
ctx: Context = None,
api_key: str = None
) -> Dict[str, Any]:
"""
Get a specific article by title.
"""
if not api_key:
logger.error(f"Missing API key for get_article_by_title: title={title}")
raise MCPError("API key is required for this operation. Please provide a Dev.to API key in your server environment.", 401)
try:
client = DevToClient(api_key=api_key)
try:
articles = await search_articles(title)
article = next((article for article in articles if article["title"] == title), None)
if article is None:
articles = await find_all_my_articles(api_key=api_key)
article = next((article for article in articles if article.get("title", "").lower() == title.lower()), None)
if article is None:
raise MCPError(f"Article not found with title: {title}", 404)
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
raise MCPError(f"Article not found with fallback title: {title}", 404)
else:
raise
return format_article_detail(article)
except Exception as e:
logger.error(f"Error getting article {title}: {str(e)}")
raise MCPError(f"Failed to get article {title}: {str(e)}")
@mcp.tool()
async def get_user_profile(
username: Annotated[str, Field(description="The username of the Dev.to user")],
ctx: Context = None
) -> Dict[str, Any]:
"""
Get profile information for a Dev.to user.
"""
try:
# Create a client with the API key from server environment
client = DevToClient(api_key=get_api_key())
user = await client.get(f"/users/by_username?url={username}")
return format_user_profile(user)
except Exception as e:
logger.error(f"Error getting user profile for {username}: {str(e)}")
raise MCPError(f"Failed to get profile for user '{username}': {str(e)}")
@mcp.tool()
async def search_articles(
query: Annotated[str, Field(description="The search term")],
page: Annotated[int, Field(description="Starting page number for pagination")] = 1,
max_pages: Annotated[int, Field(description="Maximum number of pages to search")] = 30,
ctx: Context = None
) -> List[Dict[str, Any]]:
"""
Search for articles on Dev.to across multiple pages.
This tool will search through articles on Dev.to, looking through multiple
pages until it finds matches or reaches the maximum page limit.
"""
try:
# Create a client with the API key from server environment
client = DevToClient(api_key=get_api_key())
# Track all matching articles
all_matching_articles = []
current_page = page
max_page_to_search = page + max_pages - 1
# Report initial progress
if ctx:
await ctx.report_progress(progress=10, total=100)
# Search through pages until we find matches or reach the limit
while current_page <= max_page_to_search:
try:
# Fetch articles for the current page
articles = await client.get("/articles", params={"page": current_page})
# If we received no articles, we've reached the end
if not articles or len(articles) == 0:
break
# Filter articles containing the query in title or description
page_matches = [
article for article in articles
if (query.lower() in article.get("title", "").lower() or
query.lower() in article.get("description", "").lower() or
(isinstance(article.get("tag_list"), list) and
any(query.lower() in tag.lower() for tag in article.get("tag_list", []))) or
(isinstance(article.get("user"), dict) and
query.lower() in article.get("user", {}).get("username", "").lower()) or
query.lower() in article.get("body_markdown", "").lower())
]
# Add matching articles to our collection
all_matching_articles.extend(page_matches)
# Update progress periodically
if ctx:
progress = min(90, int(10 + (current_page - page) / max_pages * 80))
await ctx.report_progress(progress=progress, total=100)
# If we've found some matches, we can stop searching
if all_matching_articles:
break
# Move to the next page
current_page += 1
except Exception as e:
logger.warning(f"Error searching page {current_page}: {str(e)}")
# Continue to the next page even if there's an error
current_page += 1
# If we didn't find anything through pagination, try direct search approaches
if not all_matching_articles:
# Try searching by tag if the query looks like a tag
try:
tag_articles = await client.get("/articles", params={"tag": query.lower()})
all_matching_articles.extend(tag_articles)
except Exception:
# Ignore errors in fallback searches
pass
# If query looks like a username, try that
if not all_matching_articles and " " not in query:
try:
user_articles = await client.get("/articles", params={"username": query.lower()})
all_matching_articles.extend(user_articles)
except Exception:
# Ignore errors in fallback searches
pass
# Complete progress
if ctx:
await ctx.report_progress(progress=100, total=100)
# Return a simplified list of articles with essential details
simplified_articles = simplify_articles(all_matching_articles)
# Add a match_type field to indicate these are search results
for article in simplified_articles:
article["match_type"] = "search_result"
return ArticleListResponse.create(simplified_articles)
except Exception as e:
logger.error(f"Error searching articles for '{query}': {str(e)}")
raise MCPError(f"Failed to search for '{query}': {str(e)}")
@mcp.tool()
async def search_articles_by_user(
username: Annotated[str, Field(description="The Dev.to username to search articles for")],
page: Annotated[int, Field(description="Starting page number for pagination")] = 1,
per_page: Annotated[int, Field(description="Number of articles per page")] = 30,
max_pages: Annotated[int, Field(description="Maximum number of pages to search")] = 30,
ctx: Context = None
) -> List[Dict[str, Any]]:
"""
Get all articles published by a specific Dev.to user.
This tool will search through all articles by a user, looking through multiple
pages until it reaches the maximum page limit.
"""
try:
# Create a client with the API key from server environment
client = DevToClient(api_key=get_api_key())
# Track all articles across multiple pages
all_articles = []
current_page = page
max_page_to_search = page + max_pages - 1
# Report initial progress
if ctx:
await ctx.report_progress(progress=10, total=100)
# Search through pages until we reach the limit or run out of results
while current_page <= max_page_to_search:
try:
# Fetch articles for the current page
articles = await client.get("/articles", params={
"username": username,
"page": current_page,
"per_page": per_page
})
# If we received no articles, we've reached the end
if not articles or len(articles) == 0:
break
# Add articles to our collection
all_articles.extend(articles)
# Update progress periodically
if ctx:
progress = min(90, int(10 + (current_page - page) / max_pages * 80))
await ctx.report_progress(progress=progress, total=100)
# Move to the next page
current_page += 1
except Exception as e:
logger.warning(f"Error searching page {current_page} for user {username}: {str(e)}")
# Continue to the next page even if there's an error
current_page += 1
# Complete progress
if ctx:
await ctx.report_progress(progress=100, total=100)
# Return a simplified list of articles with essential details
simplified_articles = simplify_articles(all_articles)
return ArticleListResponse.create(simplified_articles)
except Exception as e:
logger.error(f"Error fetching articles for user '{username}': {str(e)}")
raise MCPError(f"Failed to get articles for user '{username}': {str(e)}")
@mcp.tool()
async def list_my_articles(
page: int = 1,
per_page: int = 30,
max_pages: int = 10,
ctx: Context = None,
api_key: str = None
) -> List[Dict[str, Any]]:
"""
List my published articles across multiple pages.
This tool will fetch my articles from Dev.to, looking through multiple
pages until it reaches the maximum page limit.
"""
try:
if api_key is None:
api_key = get_api_key()
if not api_key:
raise MCPError("API key is required for this operation. Please provide a Dev.to API key in your server environment.", 401)
# Create a client with the API key
client = DevToClient(api_key=api_key)
# Track all articles across multiple pages
all_articles = []
current_page = page
max_page_to_search = page + max_pages - 1
# Report initial progress
if ctx:
await ctx.report_progress(progress=10, total=100)
# Search through pages until we reach the limit or run out of results
while current_page <= max_page_to_search:
try:
# Fetch articles for the current page
articles = await client.get(
"/articles/me",
params={"page": current_page, "per_page": per_page}
)
# If we received no articles, we've reached the end
if not articles or len(articles) == 0:
break
# Add articles to our collection
all_articles.extend(articles)
# Update progress periodically
if ctx:
progress = min(90, int(10 + (current_page - page) / max_pages * 80))
await ctx.report_progress(progress=progress, total=100)
# Move to the next page
current_page += 1
except Exception as e:
logger.warning(f"Error fetching my articles on page {current_page}: {str(e)}")
# Continue to the next page even if there's an error
current_page += 1
# Complete progress
if ctx:
await ctx.report_progress(progress=100, total=100)
# Return a simplified list of articles with essential details
simplified_articles = simplify_articles(all_articles)
return ArticleListResponse.create(simplified_articles)
except Exception as e:
logger.error(f"Error listing user articles: {str(e)}")
raise MCPError(f"Failed to list my articles: {str(e)}")
@mcp.tool()
async def list_my_draft_articles(
page: int = 1,
per_page: int = 30,
max_pages: int = 10,
ctx: Context = None,
api_key: str = None
) -> List[Dict[str, Any]]:
"""
List my draft articles on Dev.to, paginated.
"""
try:
if api_key is None:
api_key = get_api_key()
if not api_key:
raise MCPError("API key is required for this operation. Please provide a Dev.to API key in your server environment.", 401)
client = DevToClient(api_key=api_key)
all_articles = []
current_page = page
max_page_to_search = page + max_pages - 1
while current_page <= max_page_to_search:
try:
articles = await client.get(
"/articles/me/unpublished",
params={"page": current_page, "per_page": per_page}
)
if not articles or len(articles) == 0:
break
all_articles.extend(articles)
current_page += 1
except Exception as e:
logger.warning(f"Error fetching my draft articles on page {current_page}: {str(e)}")
current_page += 1
simplified_articles = simplify_articles(all_articles)
return ArticleListResponse.create(simplified_articles)
except Exception as e:
logger.error(f"Error listing draft articles: {str(e)}")