mcp_introduce 606 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609
  1. # Example Clients
  2. Source: https://modelcontextprotocol.io/clients
  3. A list of applications that support MCP integrations
  4. This page provides an overview of applications that support the Model Context Protocol (MCP). Each client may support different MCP features, allowing for varying levels of integration with MCP servers.
  5. ## Feature support matrix
  6. <div id="feature-support-matrix-wrapper">
  7. | Client | [Resources] | [Prompts] | [Tools] | [Discovery][Discovery] | [Sampling] | Roots | Notes |
  8. | ------------------------------------------------ | ----------- | --------- | ------- | ---------------------- | ---------- | ----- | ----------------------------------------------------------------------------------------------- |
  9. | [5ire][5ire] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools. |
  10. | [AgentAI][AgentAI] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Agent Library written in Rust with tools support |
  11. | [AgenticFlow][AgenticFlow] | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | Supports tools, prompts, and resources for no-code AI agents and multi-agent workflows. |
  12. | [Amazon Q CLI][Amazon Q CLI] | ❌ | ✅ | ✅ | ❓ | ❌ | ❌ | Supports prompts and tools. |
  13. | [Apify MCP Tester][Apify MCP Tester] | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | Supports remote MCP servers and tool discovery. |
  14. | [BeeAI Framework][BeeAI Framework] | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | Supports tools in agentic workflows. |
  15. | [BoltAI][BoltAI] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools. |
  16. | [Claude.ai][Claude.ai] | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | Supports tools, prompts, and resources for remote MCP servers. |
  17. | [Claude Code][Claude Code] | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | Supports prompts and tools |
  18. | [Claude Desktop App][Claude Desktop] | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | Supports tools, prompts, and resources for local and remote MCP servers. |
  19. | [Cline][Cline] | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ | Supports tools and resources. |
  20. | [Continue][Continue] | ✅ | ✅ | ✅ | ❓ | ❌ | ❌ | Supports tools, prompts, and resources. |
  21. | [Copilot-MCP][CopilotMCP] | ✅ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools and resources. |
  22. | [Cursor][Cursor] | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | Supports tools. |
  23. | [Daydreams Agents][Daydreams] | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | Support for drop in Servers to Daydreams agents |
  24. | [Emacs Mcp][Mcp.el] | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | Supports tools in Emacs. |
  25. | [fast-agent][fast-agent] | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | Full multimodal MCP support, with end-to-end tests |
  26. | [FLUJO][FLUJO] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Support for resources, Prompts and Roots are coming soon |
  27. | [Genkit][Genkit] | ⚠️ | ✅ | ✅ | ❓ | ❌ | ❌ | Supports resource list and lookup through tools. |
  28. | [Glama][Glama] | ✅ | ✅ | ✅ | ❓ | ❌ | ❌ | Supports tools. |
  29. | [GenAIScript][GenAIScript] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools. |
  30. | [Goose][Goose] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools. |
  31. | [gptme][gptme] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools. |
  32. | [HyperAgent][HyperAgent] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools. |
  33. | [Klavis AI Slack/Discord/Web][Klavis AI] | ✅ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools and resources. |
  34. | [LibreChat][LibreChat] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools for Agents |
  35. | [Lutra][Lutra] | ✅ | ✅ | ✅ | ❓ | ❌ | ❌ | Supports any MCP server for reusable playbook creation. |
  36. | [mcp-agent][mcp-agent] | ❌ | ❌ | ✅ | ❓ | ⚠️ | ❌ | Supports tools, server connection management, and agent workflows. |
  37. | [mcp-use][mcp-use] | ✅ | ✅ | ✅ | ❓ | ❌ | ❌ | Support tools, resources, stdio & http connection, local llms-agents. |
  38. | [MCPHub][MCPHub] | ✅ | ✅ | ✅ | ❓ | ❌ | ❌ | Supports tools, resources, and prompts in Neovim |
  39. | [MCPOmni-Connect][MCPOmni-Connect] | ✅ | ✅ | ✅ | ❓ | ✅ | ❌ | Supports tools with agentic mode, ReAct, and orchestrator capabilities. |
  40. | [Microsoft Copilot Studio] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools |
  41. | [MindPal][MindPal] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools for no-code AI agents and multi-agent workflows. |
  42. | [Msty Studio][Msty Studio] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools |
  43. | [NVIDIA Agent Intelligence toolkit][AIQ toolkit] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools in agentic workflows. |
  44. | [OpenSumi][OpenSumi] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools in OpenSumi |
  45. | [oterm][oterm] | ❌ | ✅ | ✅ | ❓ | ✅ | ❌ | Supports tools, prompts and sampling for Ollama. |
  46. | [Postman][postman] | ✅ | ✅ | ✅ | ❓ | ❌ | ❌ | Supports tools, resources, prompts, and sampling |
  47. | [Roo Code][Roo Code] | ✅ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools and resources. |
  48. | [Slack MCP Client][Slack MCP Client] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools and multiple servers. |
  49. | [Sourcegraph Cody][Cody] | ✅ | ❌ | ❌ | ❓ | ❌ | ❌ | Supports resources through OpenCTX |
  50. | [SpinAI][SpinAI] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools for Typescript AI Agents |
  51. | [Superinterface][Superinterface] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools |
  52. | [Superjoin][Superjoin] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools and multiple servers. |
  53. | [TheiaAI/TheiaIDE][TheiaAI/TheiaIDE] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools for Agents in Theia AI and the AI-powered Theia IDE |
  54. | [Tome][Tome] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools, manages MCP servers. |
  55. | [TypingMind App][TypingMind App] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools at app-level (appear as plugins) or when assigned to Agents |
  56. | [VS Code GitHub Copilot][VS Code] | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | Supports dynamic tool/roots discovery, secure secret configuration, and explicit tool prompting |
  57. | [Warp][Warp] | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ | Supports tools, resources, and most of the discovery criteria |
  58. | [WhatsMPC][WhatsMPC] | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | Supports tools for Remote MCP Servers in WhatsApp |
  59. | [Windsurf Editor][Windsurf] | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | Supports tools with AI Flow for collaborative development. |
  60. | [Witsy][Witsy] | ❌ | ❌ | ✅ | ❓ | ❌ | ❌ | Supports tools in Witsy. |
  61. | [Zed][Zed] | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | Prompts appear as slash commands |
  62. | [Zencoder][Zencoder] | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | Supports tools |
  63. [5ire]: https://github.com/nanbingxyz/5ire
  64. [AgentAI]: https://github.com/AdamStrojek/rust-agentai
  65. [AgenticFlow]: https://agenticflow.ai/mcp
  66. [AIQ toolkit]: https://github.com/NVIDIA/AIQToolkit
  67. [Amazon Q CLI]: https://github.com/aws/amazon-q-developer-cli
  68. [Apify MCP Tester]: https://apify.com/jiri.spilka/tester-mcp-client
  69. [BeeAI Framework]: https://i-am-bee.github.io/beeai-framework
  70. [BoltAI]: https://boltai.com
  71. [Claude.ai]: https://claude.ai
  72. [Claude Code]: https://claude.ai/code
  73. [Claude Desktop]: https://claude.ai/download
  74. [Cline]: https://github.com/cline/cline
  75. [Continue]: https://github.com/continuedev/continue
  76. [CopilotMCP]: https://github.com/VikashLoomba/copilot-mcp
  77. [Cursor]: https://cursor.com
  78. [Daydreams]: https://github.com/daydreamsai/daydreams
  79. [Klavis AI]: https://www.klavis.ai/
  80. [Mcp.el]: https://github.com/lizqwerscott/mcp.el
  81. [fast-agent]: https://github.com/evalstate/fast-agent
  82. [FLUJO]: https://github.com/mario-andreschak/flujo
  83. [Glama]: https://glama.ai/chat
  84. [Genkit]: https://github.com/firebase/genkit
  85. [GenAIScript]: https://microsoft.github.io/genaiscript/reference/scripts/mcp-tools/
  86. [Goose]: https://block.github.io/goose/docs/goose-architecture/#interoperability-with-extensions
  87. [LibreChat]: https://github.com/danny-avila/LibreChat
  88. [Lutra]: https://lutra.ai
  89. [mcp-agent]: https://github.com/lastmile-ai/mcp-agent
  90. [mcp-use]: https://github.com/pietrozullo/mcp-use
  91. [MCPHub]: https://github.com/ravitemer/mcphub.nvim
  92. [MCPOmni-Connect]: https://github.com/Abiorh001/mcp_omni_connect
  93. [Microsoft Copilot Studio]: https://learn.microsoft.com/en-us/microsoft-copilot-studio/agent-extend-action-mcp
  94. [MindPal]: https://mindpal.io
  95. [Msty Studio]: https://msty.ai
  96. [OpenSumi]: https://github.com/opensumi/core
  97. [oterm]: https://github.com/ggozad/oterm
  98. [Postman]: https://postman.com/downloads
  99. [Roo Code]: https://roocode.com
  100. [Slack MCP Client]: https://github.com/tuannvm/slack-mcp-client
  101. [Cody]: https://sourcegraph.com/cody
  102. [SpinAI]: https://spinai.dev
  103. [Superinterface]: https://superinterface.ai
  104. [Superjoin]: https://superjoin.ai
  105. [TheiaAI/TheiaIDE]: https://eclipsesource.com/blogs/2024/12/19/theia-ide-and-theia-ai-support-mcp/
  106. [Tome]: https://github.com/runebookai/tome
  107. [TypingMind App]: https://www.typingmind.com
  108. [VS Code]: https://code.visualstudio.com/
  109. [Windsurf]: https://codeium.com/windsurf
  110. [gptme]: https://github.com/gptme/gptme
  111. [Warp]: https://www.warp.dev/
  112. [WhatsMPC]: https://wassist.app/mcp/
  113. [Witsy]: https://github.com/nbonamy/witsy
  114. [Zed]: https://zed.dev
  115. [Zencoder]: https://zencoder.ai
  116. [Resources]: https://modelcontextprotocol.io/docs/concepts/resources
  117. [Prompts]: https://modelcontextprotocol.io/docs/concepts/prompts
  118. [Tools]: https://modelcontextprotocol.io/docs/concepts/tools
  119. [Sampling]: https://modelcontextprotocol.io/docs/concepts/sampling
  120. [HyperAgent]: https://github.com/hyperbrowserai/HyperAgent
  121. [Discovery]: /docs/concepts/tools#tool-discovery-and-updates
  122. </div>
  123. ## Client details
  124. ### 5ire
  125. [5ire](https://github.com/nanbingxyz/5ire) is an open source cross-platform desktop AI assistant that supports tools through MCP servers.
  126. **Key features:**
  127. * Built-in MCP servers can be quickly enabled and disabled.
  128. * Users can add more servers by modifying the configuration file.
  129. * It is open-source and user-friendly, suitable for beginners.
  130. * Future support for MCP will be continuously improved.
  131. ### AgentAI
  132. [AgentAI](https://github.com/AdamStrojek/rust-agentai) is a Rust library designed to simplify the creation of AI agents. The library includes seamless integration with MCP Servers.
  133. [Example of MCP Server integration](https://github.com/AdamStrojek/rust-agentai/blob/master/examples/tools_mcp.rs)
  134. **Key features:**
  135. * Multi-LLM – We support most LLM APIs (OpenAI, Anthropic, Gemini, Ollama, and all OpenAI API Compatible).
  136. * Built-in support for MCP Servers.
  137. * Create agentic flows in a type- and memory-safe language like Rust.
  138. ### AgenticFlow
  139. [AgenticFlow](https://agenticflow.ai/) is a no-code AI platform that helps you build agents that handle sales, marketing, and creative tasks around the clock. Connect 2,500+ APIs and 10,000+ tools securely via MCP.
  140. **Key features:**
  141. * No-code AI agent creation and workflow building.
  142. * Access a vast library of 10,000+ tools and 2,500+ APIs through MCP.
  143. * Simple 3-step process to connect MCP servers.
  144. * Securely manage connections and revoke access anytime.
  145. **Learn more:**
  146. * [AgenticFlow MCP Integration](https://agenticflow.ai/mcp)
  147. ### Amazon Q CLI
  148. [Amazon Q CLI](https://github.com/aws/amazon-q-developer-cli) is an open-source, agentic coding assistant for terminals.
  149. **Key features:**
  150. * Full support for MCP servers.
  151. * Edit prompts using your preferred text editor.
  152. * Access saved prompts instantly with `@`.
  153. * Control and organize AWS resources directly from your terminal.
  154. * Tools, profiles, context management, auto-compact, and so much more!
  155. **Get Started**
  156. ```bash
  157. brew install amazon-q
  158. ```
  159. ### Apify MCP Tester
  160. [Apify MCP Tester](https://github.com/apify/tester-mcp-client) is an open-source client that connects to any MCP server using Server-Sent Events (SSE).
  161. It is a standalone Apify Actor designed for testing MCP servers over SSE, with support for Authorization headers.
  162. It uses plain JavaScript (old-school style) and is hosted on Apify, allowing you to run it without any setup.
  163. **Key features:**
  164. * Connects to any MCP server via SSE.
  165. * Works with the [Apify MCP Server](https://apify.com/apify/actors-mcp-server) to interact with one or more Apify [Actors](https://apify.com/store).
  166. * Dynamically utilizes tools based on context and user queries (if supported by the server).
  167. ### BeeAI Framework
  168. [BeeAI Framework](https://i-am-bee.github.io/beeai-framework) is an open-source framework for building, deploying, and serving powerful agentic workflows at scale. The framework includes the **MCP Tool**, a native feature that simplifies the integration of MCP servers into agentic workflows.
  169. **Key features:**
  170. * Seamlessly incorporate MCP tools into agentic workflows.
  171. * Quickly instantiate framework-native tools from connected MCP client(s).
  172. * Planned future support for agentic MCP capabilities.
  173. **Learn more:**
  174. * [Example of using MCP tools in agentic workflow](https://i-am-bee.github.io/beeai-framework/#/typescript/tools?id=using-the-mcptool-class)
  175. ### BoltAI
  176. [BoltAI](https://boltai.com) is a native, all-in-one AI chat client with MCP support. BoltAI supports multiple AI providers (OpenAI, Anthropic, Google AI...), including local AI models (via Ollama, LM Studio or LMX)
  177. **Key features:**
  178. * MCP Tool integrations: once configured, user can enable individual MCP server in each chat
  179. * MCP quick setup: import configuration from Claude Desktop app or Cursor editor
  180. * Invoke MCP tools inside any app with AI Command feature
  181. * Integrate with remote MCP servers in the mobile app
  182. **Learn more:**
  183. * [BoltAI docs](https://boltai.com/docs/plugins/mcp-servers)
  184. * [BoltAI website](https://boltai.com)
  185. ### Claude Code
  186. Claude Code is an interactive agentic coding tool from Anthropic that helps you code faster through natural language commands. It supports MCP integration for prompts and tools, and also functions as an MCP server to integrate with other clients.
  187. **Key features:**
  188. * Tool and prompt support for MCP servers
  189. * Offers its own tools through an MCP server for integrating with other MCP clients
  190. ### Claude.ai
  191. [Claude.ai](https://claude.ai) is Anthropic's web-based AI assistant that provides MCP support for remote servers.
  192. **Key features:**
  193. * Support for remote MCP servers via integrations UI in settings
  194. * Access to tools, prompts, and resources from configured MCP servers
  195. * Seamless integration with Claude's conversational interface
  196. * Enterprise-grade security and compliance features
  197. ### Claude Desktop App
  198. The Claude desktop application provides comprehensive support for MCP, enabling deep integration with local tools and data sources.
  199. **Key features:**
  200. * Full support for resources, allowing attachment of local files and data
  201. * Support for prompt templates
  202. * Tool integration for executing commands and scripts
  203. * Local server connections for enhanced privacy and security
  204. ### Cline
  205. [Cline](https://github.com/cline/cline) is an autonomous coding agent in VS Code that edits files, runs commands, uses a browser, and more–with your permission at each step.
  206. **Key features:**
  207. * Create and add tools through natural language (e.g. "add a tool that searches the web")
  208. * Share custom MCP servers Cline creates with others via the `~/Documents/Cline/MCP` directory
  209. * Displays configured MCP servers along with their tools, resources, and any error logs
  210. ### Continue
  211. [Continue](https://github.com/continuedev/continue) is an open-source AI code assistant, with built-in support for all MCP features.
  212. **Key features:**
  213. * Type "@" to mention MCP resources
  214. * Prompt templates surface as slash commands
  215. * Use both built-in and MCP tools directly in chat
  216. * Supports VS Code and JetBrains IDEs, with any LLM
  217. ### Copilot-MCP
  218. [Copilot-MCP](https://github.com/VikashLoomba/copilot-mcp) enables AI coding assistance via MCP.
  219. **Key features:**
  220. * Support for MCP tools and resources
  221. * Integration with development workflows
  222. * Extensible AI capabilities
  223. ### Cursor
  224. [Cursor](https://docs.cursor.com/advanced/model-context-protocol) is an AI code editor.
  225. **Key features:**
  226. * Support for MCP tools in Cursor Composer
  227. * Support for both STDIO and SSE
  228. ### Daydreams
  229. [Daydreams](https://github.com/daydreamsai/daydreams) is a generative agent framework for executing anything onchain
  230. **Key features:**
  231. * Supports MCP Servers in config
  232. * Exposes MCP Client
  233. ### Emacs Mcp
  234. [Emacs Mcp](https://github.com/lizqwerscott/mcp.el) is an Emacs client designed to interface with MCP servers, enabling seamless connections and interactions. It provides MCP tool invocation support for AI plugins like [gptel](https://github.com/karthink/gptel) and [llm](https://github.com/ahyatt/llm), adhering to Emacs' standard tool invocation format. This integration enhances the functionality of AI tools within the Emacs ecosystem.
  235. **Key features:**
  236. * Provides MCP tool support for Emacs.
  237. ### fast-agent
  238. [fast-agent](https://github.com/evalstate/fast-agent) is a Python Agent framework, with simple declarative support for creating Agents and Workflows, with full multi-modal support for Anthropic and OpenAI models.
  239. **Key features:**
  240. * PDF and Image support, based on MCP Native types
  241. * Interactive front-end to develop and diagnose Agent applications, including passthrough and playback simulators
  242. * Built in support for "Building Effective Agents" workflows.
  243. * Deploy Agents as MCP Servers
  244. ### FLUJO
  245. Think n8n + ChatGPT. FLUJO is an desktop application that integrates with MCP to provide a workflow-builder interface for AI interactions. Built with Next.js and React, it supports both online and offline (ollama) models, it manages API Keys and environment variables centrally and can install MCP Servers from GitHub. FLUJO has an ChatCompletions endpoint and flows can be executed from other AI applications like Cline, Roo or Claude.
  246. **Key features:**
  247. * Environment & API Key Management
  248. * Model Management
  249. * MCP Server Integration
  250. * Workflow Orchestration
  251. * Chat Interface
  252. ### Genkit
  253. [Genkit](https://github.com/firebase/genkit) is a cross-language SDK for building and integrating GenAI features into applications. The [genkitx-mcp](https://github.com/firebase/genkit/tree/main/js/plugins/mcp) plugin enables consuming MCP servers as a client or creating MCP servers from Genkit tools and prompts.
  254. **Key features:**
  255. * Client support for tools and prompts (resources partially supported)
  256. * Rich discovery with support in Genkit's Dev UI playground
  257. * Seamless interoperability with Genkit's existing tools and prompts
  258. * Works across a wide variety of GenAI models from top providers
  259. ### Glama
  260. [Glama](https://glama.ai/chat) is a comprehensive AI workspace and integration platform that offers a unified interface to leading LLM providers, including OpenAI, Anthropic, and others. It supports the Model Context Protocol (MCP) ecosystem, enabling developers and enterprises to easily discover, build, and manage MCP servers.
  261. **Key features:**
  262. * Integrated [MCP Server Directory](https://glama.ai/mcp/servers)
  263. * Integrated [MCP Tool Directory](https://glama.ai/mcp/tools)
  264. * Host MCP servers and access them via the Chat or SSE endpoints
  265. – Ability to chat with multiple LLMs and MCP servers at once
  266. * Upload and analyze local files and data
  267. * Full-text search across all your chats and data
  268. ### GenAIScript
  269. Programmatically assemble prompts for LLMs using [GenAIScript](https://microsoft.github.io/genaiscript/) (in JavaScript). Orchestrate LLMs, tools, and data in JavaScript.
  270. **Key features:**
  271. * JavaScript toolbox to work with prompts
  272. * Abstraction to make it easy and productive
  273. * Seamless Visual Studio Code integration
  274. ### Goose
  275. [Goose](https://github.com/block/goose) is an open source AI agent that supercharges your software development by automating coding tasks.
  276. **Key features:**
  277. * Expose MCP functionality to Goose through tools.
  278. * MCPs can be installed directly via the [extensions directory](https://block.github.io/goose/v1/extensions/), CLI, or UI.
  279. * Goose allows you to extend its functionality by [building your own MCP servers](https://block.github.io/goose/docs/tutorials/custom-extensions).
  280. * Includes built-in tools for development, web scraping, automation, memory, and integrations with JetBrains and Google Drive.
  281. ### gptme
  282. [gptme](https://github.com/gptme/gptme) is a open-source terminal-based personal AI assistant/agent, designed to assist with programming tasks and general knowledge work.
  283. **Key features:**
  284. * CLI-first design with a focus on simplicity and ease of use
  285. * Rich set of built-in tools for shell commands, Python execution, file operations, and web browsing
  286. * Local-first approach with support for multiple LLM providers
  287. * Open-source, built to be extensible and easy to modify
  288. ### HyperAgent
  289. [HyperAgent](https://github.com/hyperbrowserai/HyperAgent) is Playwright supercharged with AI. With HyperAgent, you no longer need brittle scripts, just powerful natural language commands. Using MCP servers, you can extend the capability of HyperAgent, without having to write any code.
  290. **Key features:**
  291. * AI Commands: Simple APIs like page.ai(), page.extract() and executeTask() for any AI automation
  292. * Fallback to Regular Playwright: Use regular Playwright when AI isn't needed
  293. * Stealth Mode – Avoid detection with built-in anti-bot patches
  294. * Cloud Ready – Instantly scale to hundreds of sessions via [Hyperbrowser](https://www.hyperbrowser.ai/)
  295. * MCP Client – Connect to tools like Composio for full workflows (e.g. writing web data to Google Sheets)
  296. ### Klavis AI Slack/Discord/Web
  297. [Klavis AI](https://www.klavis.ai/) is an Open-Source Infra to Use, Build & Scale MCPs with ease.
  298. **Key features:**
  299. * Slack/Discord/Web MCP clients for using MCPs directly
  300. * Simple web UI dashboard for easy MCP configuration
  301. * Direct OAuth integration with Slack & Discord Clients and MCP Servers for secure user authentication
  302. * SSE transport support
  303. * Open-source infrastructure ([GitHub repository](https://github.com/Klavis-AI/klavis))
  304. **Learn more:**
  305. * [Demo video showing MCP usage in Slack/Discord](https://youtu.be/9-QQAhrQWw8)
  306. ### LibreChat
  307. [LibreChat](https://github.com/danny-avila/LibreChat) is an open-source, customizable AI chat UI that supports multiple AI providers, now including MCP integration.
  308. **Key features:**
  309. * Extend current tool ecosystem, including [Code Interpreter](https://www.librechat.ai/docs/features/code_interpreter) and Image generation tools, through MCP servers
  310. * Add tools to customizable [Agents](https://www.librechat.ai/docs/features/agents), using a variety of LLMs from top providers
  311. * Open-source and self-hostable, with secure multi-user support
  312. * Future roadmap includes expanded MCP feature support
  313. ### Lutra
  314. [Lutra](https://lutra.ai) is an AI agent that transforms conversations into actionable, automated workflows.
  315. **Key features:**
  316. * Easy MCP Integration: Connecting Lutra to MCP servers is as simple as providing the server URL; Lutra handles the rest behind the scenes.
  317. * Chat to Take Action: Lutra understands your conversational context and goals, automatically integrating with your existing apps to perform tasks.
  318. * Reusable Playbooks: After completing a task, save the steps as reusable, automated workflows—simplifying repeatable processes and reducing manual effort.
  319. * Shareable Automations: Easily share your saved playbooks with teammates to standardize best practices and accelerate collaborative workflows.
  320. **Learn more:**
  321. * [Lutra AI agent explained](https://www.youtube.com/watch?v=W5ZpN0cMY70)
  322. ### mcp-agent
  323. [mcp-agent] is a simple, composable framework to build agents using Model Context Protocol.
  324. **Key features:**
  325. * Automatic connection management of MCP servers.
  326. * Expose tools from multiple servers to an LLM.
  327. * Implements every pattern defined in [Building Effective Agents](https://www.anthropic.com/research/building-effective-agents).
  328. * Supports workflow pause/resume signals, such as waiting for human feedback.
  329. ### mcp-use
  330. [mcp-use] is an open source python library to very easily connect any LLM to any MCP server both locally and remotely.
  331. **Key features:**
  332. * Very simple interface to connect any LLM to any MCP.
  333. * Support the creation of custom agents, workflows.
  334. * Supports connection to multiple MCP servers simultaneously.
  335. * Supports all langchain supported models, also locally.
  336. * Offers efficient tool orchestration and search functionalities.
  337. ### MCPHub
  338. [MCPHub] is a powerful Neovim plugin that integrates MCP (Model Context Protocol) servers into your workflow.
  339. **Key features:**
  340. * Install, configure and manage MCP servers with an intuitive UI.
  341. * Built-in Neovim MCP server with support for file operations (read, write, search, replace), command execution, terminal integration, LSP integration, buffers, and diagnostics.
  342. * Create Lua-based MCP servers directly in Neovim.
  343. * Inegrates with popular Neovim chat plugins Avante.nvim and CodeCompanion.nvim
  344. ### MCPOmni-Connect
  345. [MCPOmni-Connect](https://github.com/Abiorh001/mcp_omni_connect) is a versatile command-line interface (CLI) client designed to connect to various Model Context Protocol (MCP) servers using both stdio and SSE transport.
  346. **Key features:**
  347. * Support for resources, prompts, tools, and sampling
  348. * Agentic mode with ReAct and orchestrator capabilities
  349. * Seamless integration with OpenAI models and other LLMs
  350. * Dynamic tool and resource management across multiple servers
  351. * Support for both stdio and SSE transport protocols
  352. * Comprehensive tool orchestration and resource analysis capabilities
  353. ### Microsoft Copilot Studio
  354. [Microsoft Copilot Studio] is a robust SaaS platform designed for building custom AI-driven applications and intelligent agents, empowering developers to create, deploy, and manage sophisticated AI solutions.
  355. **Key features:**
  356. * Support for MCP tools
  357. * Extend Copilot Studio agents with MCP servers
  358. * Leveraging Microsoft unified, governed, and secure API management solutions
  359. ### MindPal
  360. [MindPal](https://mindpal.io) is a no-code platform for building and running AI agents and multi-agent workflows for business processes.
  361. **Key features:**
  362. * Build custom AI agents with no-code
  363. * Connect any SSE MCP server to extend agent tools
  364. * Create multi-agent workflows for complex business processes
  365. * User-friendly for both technical and non-technical professionals
  366. * Ongoing development with continuous improvement of MCP support
  367. **Learn more:**
  368. * [MindPal MCP Documentation](https://docs.mindpal.io/agent/mcp)
  369. ### Msty Studio
  370. [Msty Studio](https://msty.ai) is a privacy-first AI productivity platform that seamlessly integrates local and online language models (LLMs) into customizable workflows. Designed for both technical and non-technical users, Msty Studio offers a suite of tools to enhance AI interactions, automate tasks, and maintain full control over data and model behavior.
  371. **Key features:**
  372. * **Toolbox & Toolsets**: Connect AI models to local tools and scripts using MCP-compliant configurations. Group tools into Toolsets to enable dynamic, multi-step workflows within conversations.
  373. * **Turnstiles**: Create automated, multi-step AI interactions, allowing for complex data processing and decision-making flows.
  374. * **Real-Time Data Integration**: Enhance AI responses with up-to-date information by integrating real-time web search capabilities.
  375. * **Split Chats & Branching**: Engage in parallel conversations with multiple models simultaneously, enabling comparative analysis and diverse perspectives.
  376. **Learn more:**
  377. * [Msty Studio Documentation](https://docs.msty.studio/features/toolbox/tools)
  378. ### NVIDIA Agent Intelligence (AIQ) toolkit
  379. [NVIDIA Agent Intelligence (AIQ) toolkit](https://github.com/NVIDIA/AIQToolkit) is a flexible, lightweight, and unifying library that allows you to easily connect existing enterprise agents to data sources and tools across any framework.
  380. **Key features:**
  381. * Acts as an MCP **client** to consume remote tools
  382. * Acts as an MCP **server** to expose tools
  383. * Framework agnostic and compatible with LangChain, CrewAI, Semantic Kernel, and custom agents
  384. * Includes built-in observability and evaluation tools
  385. **Learn more:**
  386. * [AIQ toolkit GitHub repository](https://github.com/NVIDIA/AIQToolkit)
  387. * [AIQ toolkit MCP documentation](https://docs.nvidia.com/aiqtoolkit/latest/workflows/mcp/index.html)
  388. ### OpenSumi
  389. [OpenSumi](https://github.com/opensumi/core) is a framework helps you quickly build AI Native IDE products.
  390. **Key features:**
  391. * Supports MCP tools in OpenSumi
  392. * Supports built-in IDE MCP servers and custom MCP servers
  393. ### oterm
  394. [oterm] is a terminal client for Ollama allowing users to create chats/agents.
  395. **Key features:**
  396. * Support for multiple fully customizable chat sessions with Ollama connected with tools.
  397. * Support for MCP tools.
  398. ### Roo Code
  399. [Roo Code](https://roocode.com) enables AI coding assistance via MCP.
  400. **Key features:**
  401. * Support for MCP tools and resources
  402. * Integration with development workflows
  403. * Extensible AI capabilities
  404. ### Postman
  405. [Postman](https://postman.com/downloads) is the most popular API client and now supports MCP server testing and debugging.
  406. **Key features:**
  407. * Full support of all major MCP features (tools, prompts, resources, and subscriptions)
  408. * Fast, seamless UI for debugging MCP capabilities
  409. * MCP config integration (Claude, VSCode, etc.) for fast first-time experience in testing MCPs
  410. * Integration with history, varibles, and collections for re-use and collaboration
  411. ### Slack MCP Client
  412. [Slack MCP Client](https://github.com/tuannvm/slack-mcp-client) acts as a bridge between Slack and Model Context Protocol (MCP) servers. Using Slack as the interface, it enables large language models (LLMs) to connect and interact with various MCP servers through standardized MCP tools.
  413. **Key features:**
  414. * **Supports Popular LLM Providers:** Integrates seamlessly with leading large language model providers such as OpenAI, Anthropic, and Ollama, allowing users to leverage advanced conversational AI and orchestration capabilities within Slack.
  415. * **Dynamic and Secure Integration:** Supports dynamic registration of MCP tools, works in both channels and direct messages and manages credentials securely via environment variables or Kubernetes secrets.
  416. * **Easy Deployment and Extensibility:** Offers official Docker images, a Helm chart for Kubernetes, and Docker Compose for local development, making it simple to deploy, configure, and extend with additional MCP servers or tools.
  417. ### Sourcegraph Cody
  418. [Cody](https://openctx.org/docs/providers/modelcontextprotocol) is Sourcegraph's AI coding assistant, which implements MCP through OpenCTX.
  419. **Key features:**
  420. * Support for MCP resources
  421. * Integration with Sourcegraph's code intelligence
  422. * Uses OpenCTX as an abstraction layer
  423. * Future support planned for additional MCP features
  424. ### SpinAI
  425. [SpinAI](https://spinai.dev) is an open-source TypeScript framework for building observable AI agents. The framework provides native MCP compatibility, allowing agents to seamlessly integrate with MCP servers and tools.
  426. **Key features:**
  427. * Built-in MCP compatibility for AI agents
  428. * Open-source TypeScript framework
  429. * Observable agent architecture
  430. * Native support for MCP tools integration
  431. ### Superinterface
  432. [Superinterface](https://superinterface.ai) is AI infrastructure and a developer platform to build in-app AI assistants with support for MCP, interactive components, client-side function calling and more.
  433. **Key features:**
  434. * Use tools from MCP servers in assistants embedded via React components or script tags
  435. * SSE transport support
  436. * Use any AI model from any AI provider (OpenAI, Anthropic, Ollama, others)
  437. ### Superjoin
  438. [Superjoin](https://superjoin.ai) brings the power of MCP directly into Google Sheets extension. With Superjoin, users can access and invoke MCP tools and agents without leaving their spreadsheets, enabling powerful AI workflows and automation right where their data lives.
  439. **Key features:**
  440. * Native Google Sheets add-on providing effortless access to MCP capabilities
  441. * Supports OAuth 2.1 and header-based authentication for secure and flexible connections
  442. * Compatible with both SSE and Streamable HTTP transport for efficient, real-time streaming communication
  443. * Fully web-based, cross-platform client requiring no additional software installation
  444. ### TheiaAI/TheiaIDE
  445. [Theia AI](https://eclipsesource.com/blogs/2024/10/07/introducing-theia-ai/) is a framework for building AI-enhanced tools and IDEs. The [AI-powered Theia IDE](https://eclipsesource.com/blogs/2024/10/08/introducting-ai-theia-ide/) is an open and flexible development environment built on Theia AI.
  446. **Key features:**
  447. * **Tool Integration**: Theia AI enables AI agents, including those in the Theia IDE, to utilize MCP servers for seamless tool interaction.
  448. * **Customizable Prompts**: The Theia IDE allows users to define and adapt prompts, dynamically integrating MCP servers for tailored workflows.
  449. * **Custom agents**: The Theia IDE supports creating custom agents that leverage MCP capabilities, enabling users to design dedicated workflows on the fly.
  450. Theia AI and Theia IDE's MCP integration provide users with flexibility, making them powerful platforms for exploring and adapting MCP.
  451. **Learn more:**
  452. * [Theia IDE and Theia AI MCP Announcement](https://eclipsesource.com/blogs/2024/12/19/theia-ide-and-theia-ai-support-mcp/)
  453. * [Download the AI-powered Theia IDE](https://theia-ide.org/)
  454. ### Tome
  455. [Tome](https://github.com/runebookai/tome) is an open source cross-platform desktop app designed for working with local LLMs and MCP servers. It is designed to be beginner friendly and abstract away the nitty gritty of configuration for people getting started with MCP.
  456. **Key features:**
  457. * MCP servers are managed by Tome so there is no need to install uv or npm or configure JSON
  458. * Users can quickly add or remove MCP servers via UI
  459. * Any tool-supported local model on Ollama is compatible
  460. ### TypingMind App
  461. [TypingMind](https://www.typingmind.com) is an advanced frontend for LLMs with MCP support. TypingMind supports all popular LLM providers like OpenAI, Gemini, Claude, and users can use with their own API keys.
  462. **Key features:**
  463. * **MCP Tool Integration**: Once MCP is configured, MCP tools will show up as plugins that can be enabled/disabled easily via the main app interface.
  464. * **Assign MCP Tools to Agents**: TypingMind allows users to create AI agents that have a set of MCP servers assigned.
  465. * **Remote MCP servers**: Allows users to customize where to run the MCP servers via its MCP Connector configuration, allowing the use of MCP tools across multiple devices (laptop, mobile devices, etc.) or control MCP servers from a remote private server.
  466. **Learn more:**
  467. * [TypingMind MCP Document](https://www.typingmind.com/mcp)
  468. * [Download TypingMind (PWA)](https://www.typingmind.com/)
  469. ### VS Code GitHub Copilot
  470. [VS Code](https://code.visualstudio.com/) integrates MCP with GitHub Copilot through [agent mode](https://code.visualstudio.com/docs/copilot/chat/chat-agent-mode), allowing direct interaction with MCP-provided tools within your agentic coding workflow. Configure servers in Claude Desktop, workspace or user settings, with guided MCP installation and secure handling of keys in input variables to avoid leaking hard-coded keys.
  471. **Key features:**
  472. * Support for stdio and server-sent events (SSE) transport
  473. * Per-session selection of tools per agent session for optimal performance
  474. * Easy server debugging with restart commands and output logging
  475. * Tool calls with editable inputs and always-allow toggle
  476. * Integration with existing VS Code extension system to register MCP servers from extensions
  477. ### Warp
  478. [Warp](https://www.warp.dev/) is the intelligent terminal with AI and your dev team's knowledge built-in. With natural language capabilities integrated directly into an agentic command line, Warp enables developers to code, automate, and collaborate more efficiently -- all within a terminal that features a modern UX.
  479. **Key features:**
  480. * **Agent Mode with MCP support**: invoke tools and access data from MCP servers using natural language prompts
  481. * **Flexible server management**: add and manage CLI or SSE-based MCP servers via Warp's built-in UI
  482. * **Live tool/resource discovery**: view tools and resources from each running MCP server
  483. * **Configurable startup**: set MCP servers to start automatically with Warp or launch them manually as needed
  484. ### WhatsMPC
  485. [WhatsMPC](https://wassist.app/mcp/) is an MCP client for WhatsApp. WhatsMCP lets you interact with your AI stack from the comfort of a WhatsApp chat.
  486. **Key features:**
  487. * Supports MCP tools
  488. * SSE transport, full OAuth2 support
  489. * Chat flow management for WhatsApp messages
  490. * One click setup for connecting to your MCP servers
  491. * In chat management of MCP servers
  492. * Oauth flow natively supported in WhatsApp
  493. ### Windsurf Editor
  494. [Windsurf Editor](https://codeium.com/windsurf) is an agentic IDE that combines AI assistance with developer workflows. It features an innovative AI Flow system that enables both collaborative and independent AI interactions while maintaining developer control.
  495. **Key features:**
  496. * Revolutionary AI Flow paradigm for human-AI collaboration
  497. * Intelligent code generation and understanding
  498. * Rich development tools with multi-model support
  499. ### Witsy
  500. [Witsy](https://github.com/nbonamy/witsy) is an AI desktop assistant, supoorting Anthropic models and MCP servers as LLM tools.
  501. **Key features:**
  502. * Multiple MCP servers support
  503. * Tool integration for executing commands and scripts
  504. * Local server connections for enhanced privacy and security
  505. * Easy-install from Smithery.ai
  506. * Open-source, available for macOS, Windows and Linux
  507. ### Zed
  508. [Zed](https://zed.dev/docs/assistant/model-context-protocol) is a high-performance code editor with built-in MCP support, focusing on prompt templates and tool integration.
  509. **Key features:**
  510. * Prompt templates surface as slash commands in the editor
  511. * Tool integration for enhanced coding workflows
  512. * Tight integration with editor features and workspace context
  513. * Does not support MCP resources
  514. ### Zencoder
  515. [Zencoder](https://zecoder.ai) is a coding agent that's available as an extension for VS Code and JetBrains family of IDEs, meeting developers where they already work. It comes with RepoGrokking (deep contextual codebase understanding), agentic pipeline, and the ability to create and share custom agents.
  516. **Key features:**
  517. * RepoGrokking - deep contextual understanding of codebases
  518. * Agentic pipeline - runs, tests, and executes code before outputting it
  519. * Zen Agents platform - ability to build and create custom agents and share with the team
  520. * Integrated MCP tool library with one-click installations
  521. * Specialized agents for Unit and E2E Testing
  522. **Learn more:**
  523. * [Zencoder Documentation](https://docs.zencoder.ai)
  524. ## Adding MCP support to your application
  525. If you've added MCP support to your application, we encourage you to submit a pull request to add it to this list. MCP integration can provide your users with powerful contextual AI capabilities and make your application part of the growing MCP ecosystem.
  526. Benefits of adding MCP support:
  527. * Enable users to bring their own context and tools
  528. * Join a growing ecosystem of interoperable AI applications
  529. * Provide users with flexible integration options
  530. * Support local-first AI workflows
  531. To get started with implementing MCP in your application, check out our [Python](https://github.com/modelcontextprotocol/python-sdk) or [TypeScript SDK Documentation](https://github.com/modelcontextprotocol/typescript-sdk)
  532. ## Updates and corrections
  533. This list is maintained by the community. If you notice any inaccuracies or would like to update information about MCP support in your application, please submit a pull request or [open an issue in our documentation repository](https://github.com/modelcontextprotocol/modelcontextprotocol/issues).
  534. # Contributing
  535. Source: https://modelcontextprotocol.io/development/contributing
  536. How to participate in Model Context Protocol development
  537. We welcome contributions from the community! Please review our [contributing guidelines](https://github.com/modelcontextprotocol/.github/blob/main/CONTRIBUTING.md) for details on how to submit changes.
  538. All contributors must adhere to our [Code of Conduct](https://github.com/modelcontextprotocol/.github/blob/main/CODE_OF_CONDUCT.md).
  539. For questions and discussions, please use [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions).
  540. # Roadmap
  541. Source: https://modelcontextprotocol.io/development/roadmap
  542. Our plans for evolving Model Context Protocol
  543. <Info>Last updated: **2025-03-27**</Info>
  544. The Model Context Protocol is rapidly evolving. This page outlines our current thinking on key priorities and direction for approximately **the next six months**, though these may change significantly as the project develops. To see what's changed recently, check out the **[specification changelog](/specification/2025-03-26/changelog/)**.
  545. <Note>
  546. The ideas presented here are not commitments—we may solve these challenges differently than described, or some may not materialize at all. This is also not an *exhaustive* list; we may incorporate work that isn't mentioned here.
  547. </Note>
  548. We value community participation! Each section links to relevant discussions where you can learn more and contribute your thoughts.
  549. For a technical view of our standardization process, visit the [Standards Track](https://github.com/orgs/modelcontextprotocol/projects/2/views/2) on GitHub, which tracks how proposals progress toward inclusion in the official [MCP specification](https://spec.modelcontextprotocol.io).
  550. ## Validation
  551. To foster a robust developer ecosystem, we plan to invest in:
  552. * **Reference Client Implementations**: demonstrating protocol features with high-quality AI applications
  553. * **Compliance Test Suites**: automated verification that clients, servers, and SDKs properly implement the specification
  554. These tools will help developers confidently implement MCP while ensuring consistent behavior across the ecosystem.
  555. ## Registry
  556. For MCP to reach its full potential, we need streamlined ways to distribute and discover MCP servers.
  557. We plan to develop an [**MCP Registry**](https://github.com/orgs/modelcontextprotocol/discussions/159) that will enable centralized server discovery and metadata. This registry will primarily function as an API layer that third-party marketplaces and discovery services can build upon.
  558. ## Agents
  559. As MCP increasingly becomes part of agentic workflows, we're exploring [improvements](https://github.com/modelcontextprotocol/specification/discussions/111) such as:
  560. * **[Agent Graphs](https://github.com/modelcontextprotocol/specification/discussions/94)**: enabling complex agent topologies through namespacing and graph-aware communication patterns
  561. * **Interactive Workflows**: improving human-in-the-loop experiences with granular permissioning, standardized interaction patterns, and [ways to directly communicate](https://github.com/modelcontextprotocol/specification/issues/97) with the end user
  562. ## Multimodality
  563. Supporting the full spectrum of AI capabilities in MCP, including:
  564. * **Additional Modalities**: video and other media types
  565. * **[Streaming](https://github.com/modelcontextprotocol/specification/issues/117)**: multipart, chunked messages, and bidirectional communication for interactive experiences
  566. ## Governance
  567. We're implementing governance structures that prioritize:
  568. * **Community-Led Development**: fostering a collaborative ecosystem where community members and AI developers can all participate in MCP's evolution, ensuring it serves diverse applications and use cases
  569. * **Transparent Standardization**: establishing clear processes for contributing to the specification, while exploring formal standardization via industry bodies
  570. ## Get Involved
  571. We welcome your contributions to MCP's future! Join our [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions) to share ideas, provide feedback, or participate in the development process.
  572. # Core architecture
  573. Source: https://modelcontextprotocol.io/docs/concepts/architecture
  574. Understand how MCP connects clients, servers, and LLMs
  575. The Model Context Protocol (MCP) is built on a flexible, extensible architecture that enables seamless communication between LLM applications and integrations. This document covers the core architectural components and concepts.
  576. ## Overview
  577. MCP follows a client-server architecture where:
  578. * **Hosts** are LLM applications (like Claude Desktop or IDEs) that initiate connections
  579. * **Clients** maintain 1:1 connections with servers, inside the host application
  580. * **Servers** provide context, tools, and prompts to clients
  581. ```mermaid
  582. flowchart LR
  583. subgraph "Host"
  584. client1[MCP Client]
  585. client2[MCP Client]
  586. end
  587. subgraph "Server Process"
  588. server1[MCP Server]
  589. end
  590. subgraph "Server Process"
  591. server2[MCP Server]
  592. end
  593. client1 <-->|Transport Layer| server1
  594. client2 <-->|Transport Layer| server2
  595. ```
  596. ## Core components
  597. ### Protocol layer
  598. The protocol layer handles message framing, request/response linking, and high-level communication patterns.
  599. <Tabs>
  600. <Tab title="TypeScript">
  601. ```typescript
  602. class Protocol<Request, Notification, Result> {
  603. // Handle incoming requests
  604. setRequestHandler<T>(schema: T, handler: (request: T, extra: RequestHandlerExtra) => Promise<Result>): void
  605. // Handle incoming notifications
  606. setNotificationHandler<T>(schema: T, handler: (notification: T) => Promise<void>): void
  607. // Send requests and await responses
  608. request<T>(request: Request, schema: T, options?: RequestOptions): Promise<T>
  609. // Send one-way notifications
  610. notification(notification: Notification): Promise<void>
  611. }
  612. ```
  613. </Tab>
  614. <Tab title="Python">
  615. ```python
  616. class Session(BaseSession[RequestT, NotificationT, ResultT]):
  617. async def send_request(
  618. self,
  619. request: RequestT,
  620. result_type: type[Result]
  621. ) -> Result:
  622. """Send request and wait for response. Raises McpError if response contains error."""
  623. # Request handling implementation
  624. async def send_notification(
  625. self,
  626. notification: NotificationT
  627. ) -> None:
  628. """Send one-way notification that doesn't expect response."""
  629. # Notification handling implementation
  630. async def _received_request(
  631. self,
  632. responder: RequestResponder[ReceiveRequestT, ResultT]
  633. ) -> None:
  634. """Handle incoming request from other side."""
  635. # Request handling implementation
  636. async def _received_notification(
  637. self,
  638. notification: ReceiveNotificationT
  639. ) -> None:
  640. """Handle incoming notification from other side."""
  641. # Notification handling implementation
  642. ```
  643. </Tab>
  644. </Tabs>
  645. Key classes include:
  646. * `Protocol`
  647. * `Client`
  648. * `Server`
  649. ### Transport layer
  650. The transport layer handles the actual communication between clients and servers. MCP supports multiple transport mechanisms:
  651. 1. **Stdio transport**
  652. * Uses standard input/output for communication
  653. * Ideal for local processes
  654. 2. **Streamable HTTP transport**
  655. * Uses HTTP with optional Server-Sent Events for streaming
  656. * HTTP POST for client-to-server messages
  657. All transports use [JSON-RPC](https://www.jsonrpc.org/) 2.0 to exchange messages. See the [specification](/specification/) for detailed information about the Model Context Protocol message format.
  658. ### Message types
  659. MCP has these main types of messages:
  660. 1. **Requests** expect a response from the other side:
  661. ```typescript
  662. interface Request {
  663. method: string;
  664. params?: { ... };
  665. }
  666. ```
  667. 2. **Results** are successful responses to requests:
  668. ```typescript
  669. interface Result {
  670. [key: string]: unknown;
  671. }
  672. ```
  673. 3. **Errors** indicate that a request failed:
  674. ```typescript
  675. interface Error {
  676. code: number;
  677. message: string;
  678. data?: unknown;
  679. }
  680. ```
  681. 4. **Notifications** are one-way messages that don't expect a response:
  682. ```typescript
  683. interface Notification {
  684. method: string;
  685. params?: { ... };
  686. }
  687. ```
  688. ## Connection lifecycle
  689. ### 1. Initialization
  690. ```mermaid
  691. sequenceDiagram
  692. participant Client
  693. participant Server
  694. Client->>Server: initialize request
  695. Server->>Client: initialize response
  696. Client->>Server: initialized notification
  697. Note over Client,Server: Connection ready for use
  698. ```
  699. 1. Client sends `initialize` request with protocol version and capabilities
  700. 2. Server responds with its protocol version and capabilities
  701. 3. Client sends `initialized` notification as acknowledgment
  702. 4. Normal message exchange begins
  703. ### 2. Message exchange
  704. After initialization, the following patterns are supported:
  705. * **Request-Response**: Client or server sends requests, the other responds
  706. * **Notifications**: Either party sends one-way messages
  707. ### 3. Termination
  708. Either party can terminate the connection:
  709. * Clean shutdown via `close()`
  710. * Transport disconnection
  711. * Error conditions
  712. ## Error handling
  713. MCP defines these standard error codes:
  714. ```typescript
  715. enum ErrorCode {
  716. // Standard JSON-RPC error codes
  717. ParseError = -32700,
  718. InvalidRequest = -32600,
  719. MethodNotFound = -32601,
  720. InvalidParams = -32602,
  721. InternalError = -32603,
  722. }
  723. ```
  724. SDKs and applications can define their own error codes above -32000.
  725. Errors are propagated through:
  726. * Error responses to requests
  727. * Error events on transports
  728. * Protocol-level error handlers
  729. ## Implementation example
  730. Here's a basic example of implementing an MCP server:
  731. <Tabs>
  732. <Tab title="TypeScript">
  733. ```typescript
  734. import { Server } from "@modelcontextprotocol/sdk/server/index.js";
  735. import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
  736. const server = new Server({
  737. name: "example-server",
  738. version: "1.0.0"
  739. }, {
  740. capabilities: {
  741. resources: {}
  742. }
  743. });
  744. // Handle requests
  745. server.setRequestHandler(ListResourcesRequestSchema, async () => {
  746. return {
  747. resources: [
  748. {
  749. uri: "example://resource",
  750. name: "Example Resource"
  751. }
  752. ]
  753. };
  754. });
  755. // Connect transport
  756. const transport = new StdioServerTransport();
  757. await server.connect(transport);
  758. ```
  759. </Tab>
  760. <Tab title="Python">
  761. ```python
  762. import asyncio
  763. import mcp.types as types
  764. from mcp.server import Server
  765. from mcp.server.stdio import stdio_server
  766. app = Server("example-server")
  767. @app.list_resources()
  768. async def list_resources() -> list[types.Resource]:
  769. return [
  770. types.Resource(
  771. uri="example://resource",
  772. name="Example Resource"
  773. )
  774. ]
  775. async def main():
  776. async with stdio_server() as streams:
  777. await app.run(
  778. streams[0],
  779. streams[1],
  780. app.create_initialization_options()
  781. )
  782. if __name__ == "__main__":
  783. asyncio.run(main())
  784. ```
  785. </Tab>
  786. </Tabs>
  787. ## Best practices
  788. ### Transport selection
  789. 1. **Local communication**
  790. * Use stdio transport for local processes
  791. * Efficient for same-machine communication
  792. * Simple process management
  793. 2. **Remote communication**
  794. * Use Streamable HTTP for scenarios requiring HTTP compatibility
  795. * Consider security implications including authentication and authorization
  796. ### Message handling
  797. 1. **Request processing**
  798. * Validate inputs thoroughly
  799. * Use type-safe schemas
  800. * Handle errors gracefully
  801. * Implement timeouts
  802. 2. **Progress reporting**
  803. * Use progress tokens for long operations
  804. * Report progress incrementally
  805. * Include total progress when known
  806. 3. **Error management**
  807. * Use appropriate error codes
  808. * Include helpful error messages
  809. * Clean up resources on errors
  810. ## Security considerations
  811. 1. **Transport security**
  812. * Use TLS for remote connections
  813. * Validate connection origins
  814. * Implement authentication when needed
  815. 2. **Message validation**
  816. * Validate all incoming messages
  817. * Sanitize inputs
  818. * Check message size limits
  819. * Verify JSON-RPC format
  820. 3. **Resource protection**
  821. * Implement access controls
  822. * Validate resource paths
  823. * Monitor resource usage
  824. * Rate limit requests
  825. 4. **Error handling**
  826. * Don't leak sensitive information
  827. * Log security-relevant errors
  828. * Implement proper cleanup
  829. * Handle DoS scenarios
  830. ## Debugging and monitoring
  831. 1. **Logging**
  832. * Log protocol events
  833. * Track message flow
  834. * Monitor performance
  835. * Record errors
  836. 2. **Diagnostics**
  837. * Implement health checks
  838. * Monitor connection state
  839. * Track resource usage
  840. * Profile performance
  841. 3. **Testing**
  842. * Test different transports
  843. * Verify error handling
  844. * Check edge cases
  845. * Load test servers
  846. # Prompts
  847. Source: https://modelcontextprotocol.io/docs/concepts/prompts
  848. Create reusable prompt templates and workflows
  849. Prompts enable servers to define reusable prompt templates and workflows that clients can easily surface to users and LLMs. They provide a powerful way to standardize and share common LLM interactions.
  850. <Note>
  851. Prompts are designed to be **user-controlled**, meaning they are exposed from servers to clients with the intention of the user being able to explicitly select them for use.
  852. </Note>
  853. ## Overview
  854. Prompts in MCP are predefined templates that can:
  855. * Accept dynamic arguments
  856. * Include context from resources
  857. * Chain multiple interactions
  858. * Guide specific workflows
  859. * Surface as UI elements (like slash commands)
  860. ## Prompt structure
  861. Each prompt is defined with:
  862. ```typescript
  863. {
  864. name: string; // Unique identifier for the prompt
  865. description?: string; // Human-readable description
  866. arguments?: [ // Optional list of arguments
  867. {
  868. name: string; // Argument identifier
  869. description?: string; // Argument description
  870. required?: boolean; // Whether argument is required
  871. }
  872. ]
  873. }
  874. ```
  875. ## Discovering prompts
  876. Clients can discover available prompts through the `prompts/list` endpoint:
  877. ```typescript
  878. // Request
  879. {
  880. method: "prompts/list";
  881. }
  882. // Response
  883. {
  884. prompts: [
  885. {
  886. name: "analyze-code",
  887. description: "Analyze code for potential improvements",
  888. arguments: [
  889. {
  890. name: "language",
  891. description: "Programming language",
  892. required: true,
  893. },
  894. ],
  895. },
  896. ];
  897. }
  898. ```
  899. ## Using prompts
  900. To use a prompt, clients make a `prompts/get` request:
  901. ````typescript
  902. // Request
  903. {
  904. method: "prompts/get",
  905. params: {
  906. name: "analyze-code",
  907. arguments: {
  908. language: "python"
  909. }
  910. }
  911. }
  912. // Response
  913. {
  914. description: "Analyze Python code for potential improvements",
  915. messages: [
  916. {
  917. role: "user",
  918. content: {
  919. type: "text",
  920. text: "Please analyze the following Python code for potential improvements:\n\n```python\ndef calculate_sum(numbers):\n total = 0\n for num in numbers:\n total = total + num\n return total\n\nresult = calculate_sum([1, 2, 3, 4, 5])\nprint(result)\n```"
  921. }
  922. }
  923. ]
  924. }
  925. ````
  926. ## Dynamic prompts
  927. Prompts can be dynamic and include:
  928. ### Embedded resource context
  929. ```json
  930. {
  931. "name": "analyze-project",
  932. "description": "Analyze project logs and code",
  933. "arguments": [
  934. {
  935. "name": "timeframe",
  936. "description": "Time period to analyze logs",
  937. "required": true
  938. },
  939. {
  940. "name": "fileUri",
  941. "description": "URI of code file to review",
  942. "required": true
  943. }
  944. ]
  945. }
  946. ```
  947. When handling the `prompts/get` request:
  948. ```json
  949. {
  950. "messages": [
  951. {
  952. "role": "user",
  953. "content": {
  954. "type": "text",
  955. "text": "Analyze these system logs and the code file for any issues:"
  956. }
  957. },
  958. {
  959. "role": "user",
  960. "content": {
  961. "type": "resource",
  962. "resource": {
  963. "uri": "logs://recent?timeframe=1h",
  964. "text": "[2024-03-14 15:32:11] ERROR: Connection timeout in network.py:127\n[2024-03-14 15:32:15] WARN: Retrying connection (attempt 2/3)\n[2024-03-14 15:32:20] ERROR: Max retries exceeded",
  965. "mimeType": "text/plain"
  966. }
  967. }
  968. },
  969. {
  970. "role": "user",
  971. "content": {
  972. "type": "resource",
  973. "resource": {
  974. "uri": "file:///path/to/code.py",
  975. "text": "def connect_to_service(timeout=30):\n retries = 3\n for attempt in range(retries):\n try:\n return establish_connection(timeout)\n except TimeoutError:\n if attempt == retries - 1:\n raise\n time.sleep(5)\n\ndef establish_connection(timeout):\n # Connection implementation\n pass",
  976. "mimeType": "text/x-python"
  977. }
  978. }
  979. }
  980. ]
  981. }
  982. ```
  983. ### Multi-step workflows
  984. ```typescript
  985. const debugWorkflow = {
  986. name: "debug-error",
  987. async getMessages(error: string) {
  988. return [
  989. {
  990. role: "user",
  991. content: {
  992. type: "text",
  993. text: `Here's an error I'm seeing: ${error}`,
  994. },
  995. },
  996. {
  997. role: "assistant",
  998. content: {
  999. type: "text",
  1000. text: "I'll help analyze this error. What have you tried so far?",
  1001. },
  1002. },
  1003. {
  1004. role: "user",
  1005. content: {
  1006. type: "text",
  1007. text: "I've tried restarting the service, but the error persists.",
  1008. },
  1009. },
  1010. ];
  1011. },
  1012. };
  1013. ```
  1014. ## Example implementation
  1015. Here's a complete example of implementing prompts in an MCP server:
  1016. <Tabs>
  1017. <Tab title="TypeScript">
  1018. ```typescript
  1019. import { Server } from "@modelcontextprotocol/sdk/server";
  1020. import {
  1021. ListPromptsRequestSchema,
  1022. GetPromptRequestSchema
  1023. } from "@modelcontextprotocol/sdk/types";
  1024. const PROMPTS = {
  1025. "git-commit": {
  1026. name: "git-commit",
  1027. description: "Generate a Git commit message",
  1028. arguments: [
  1029. {
  1030. name: "changes",
  1031. description: "Git diff or description of changes",
  1032. required: true
  1033. }
  1034. ]
  1035. },
  1036. "explain-code": {
  1037. name: "explain-code",
  1038. description: "Explain how code works",
  1039. arguments: [
  1040. {
  1041. name: "code",
  1042. description: "Code to explain",
  1043. required: true
  1044. },
  1045. {
  1046. name: "language",
  1047. description: "Programming language",
  1048. required: false
  1049. }
  1050. ]
  1051. }
  1052. };
  1053. const server = new Server({
  1054. name: "example-prompts-server",
  1055. version: "1.0.0"
  1056. }, {
  1057. capabilities: {
  1058. prompts: {}
  1059. }
  1060. });
  1061. // List available prompts
  1062. server.setRequestHandler(ListPromptsRequestSchema, async () => {
  1063. return {
  1064. prompts: Object.values(PROMPTS)
  1065. };
  1066. });
  1067. // Get specific prompt
  1068. server.setRequestHandler(GetPromptRequestSchema, async (request) => {
  1069. const prompt = PROMPTS[request.params.name];
  1070. if (!prompt) {
  1071. throw new Error(`Prompt not found: ${request.params.name}`);
  1072. }
  1073. if (request.params.name === "git-commit") {
  1074. return {
  1075. messages: [
  1076. {
  1077. role: "user",
  1078. content: {
  1079. type: "text",
  1080. text: `Generate a concise but descriptive commit message for these changes:\n\n${request.params.arguments?.changes}`
  1081. }
  1082. }
  1083. ]
  1084. };
  1085. }
  1086. if (request.params.name === "explain-code") {
  1087. const language = request.params.arguments?.language || "Unknown";
  1088. return {
  1089. messages: [
  1090. {
  1091. role: "user",
  1092. content: {
  1093. type: "text",
  1094. text: `Explain how this ${language} code works:\n\n${request.params.arguments?.code}`
  1095. }
  1096. }
  1097. ]
  1098. };
  1099. }
  1100. throw new Error("Prompt implementation not found");
  1101. });
  1102. ```
  1103. </Tab>
  1104. <Tab title="Python">
  1105. ```python
  1106. from mcp.server import Server
  1107. import mcp.types as types
  1108. # Define available prompts
  1109. PROMPTS = {
  1110. "git-commit": types.Prompt(
  1111. name="git-commit",
  1112. description="Generate a Git commit message",
  1113. arguments=[
  1114. types.PromptArgument(
  1115. name="changes",
  1116. description="Git diff or description of changes",
  1117. required=True
  1118. )
  1119. ],
  1120. ),
  1121. "explain-code": types.Prompt(
  1122. name="explain-code",
  1123. description="Explain how code works",
  1124. arguments=[
  1125. types.PromptArgument(
  1126. name="code",
  1127. description="Code to explain",
  1128. required=True
  1129. ),
  1130. types.PromptArgument(
  1131. name="language",
  1132. description="Programming language",
  1133. required=False
  1134. )
  1135. ],
  1136. )
  1137. }
  1138. # Initialize server
  1139. app = Server("example-prompts-server")
  1140. @app.list_prompts()
  1141. async def list_prompts() -> list[types.Prompt]:
  1142. return list(PROMPTS.values())
  1143. @app.get_prompt()
  1144. async def get_prompt(
  1145. name: str, arguments: dict[str, str] | None = None
  1146. ) -> types.GetPromptResult:
  1147. if name not in PROMPTS:
  1148. raise ValueError(f"Prompt not found: {name}")
  1149. if name == "git-commit":
  1150. changes = arguments.get("changes") if arguments else ""
  1151. return types.GetPromptResult(
  1152. messages=[
  1153. types.PromptMessage(
  1154. role="user",
  1155. content=types.TextContent(
  1156. type="text",
  1157. text=f"Generate a concise but descriptive commit message "
  1158. f"for these changes:\n\n{changes}"
  1159. )
  1160. )
  1161. ]
  1162. )
  1163. if name == "explain-code":
  1164. code = arguments.get("code") if arguments else ""
  1165. language = arguments.get("language", "Unknown") if arguments else "Unknown"
  1166. return types.GetPromptResult(
  1167. messages=[
  1168. types.PromptMessage(
  1169. role="user",
  1170. content=types.TextContent(
  1171. type="text",
  1172. text=f"Explain how this {language} code works:\n\n{code}"
  1173. )
  1174. )
  1175. ]
  1176. )
  1177. raise ValueError("Prompt implementation not found")
  1178. ```
  1179. </Tab>
  1180. </Tabs>
  1181. ## Best practices
  1182. When implementing prompts:
  1183. 1. Use clear, descriptive prompt names
  1184. 2. Provide detailed descriptions for prompts and arguments
  1185. 3. Validate all required arguments
  1186. 4. Handle missing arguments gracefully
  1187. 5. Consider versioning for prompt templates
  1188. 6. Cache dynamic content when appropriate
  1189. 7. Implement error handling
  1190. 8. Document expected argument formats
  1191. 9. Consider prompt composability
  1192. 10. Test prompts with various inputs
  1193. ## UI integration
  1194. Prompts can be surfaced in client UIs as:
  1195. * Slash commands
  1196. * Quick actions
  1197. * Context menu items
  1198. * Command palette entries
  1199. * Guided workflows
  1200. * Interactive forms
  1201. ## Updates and changes
  1202. Servers can notify clients about prompt changes:
  1203. 1. Server capability: `prompts.listChanged`
  1204. 2. Notification: `notifications/prompts/list_changed`
  1205. 3. Client re-fetches prompt list
  1206. ## Security considerations
  1207. When implementing prompts:
  1208. * Validate all arguments
  1209. * Sanitize user input
  1210. * Consider rate limiting
  1211. * Implement access controls
  1212. * Audit prompt usage
  1213. * Handle sensitive data appropriately
  1214. * Validate generated content
  1215. * Implement timeouts
  1216. * Consider prompt injection risks
  1217. * Document security requirements
  1218. # Resources
  1219. Source: https://modelcontextprotocol.io/docs/concepts/resources
  1220. Expose data and content from your servers to LLMs
  1221. Resources are a core primitive in the Model Context Protocol (MCP) that allow servers to expose data and content that can be read by clients and used as context for LLM interactions.
  1222. <Note>
  1223. Resources are designed to be **application-controlled**, meaning that the client application can decide how and when they should be used.
  1224. Different MCP clients may handle resources differently. For example:
  1225. * Claude Desktop currently requires users to explicitly select resources before they can be used
  1226. * Other clients might automatically select resources based on heuristics
  1227. * Some implementations may even allow the AI model itself to determine which resources to use
  1228. Server authors should be prepared to handle any of these interaction patterns when implementing resource support. In order to expose data to models automatically, server authors should use a **model-controlled** primitive such as [Tools](./tools).
  1229. </Note>
  1230. ## Overview
  1231. Resources represent any kind of data that an MCP server wants to make available to clients. This can include:
  1232. * File contents
  1233. * Database records
  1234. * API responses
  1235. * Live system data
  1236. * Screenshots and images
  1237. * Log files
  1238. * And more
  1239. Each resource is identified by a unique URI and can contain either text or binary data.
  1240. ## Resource URIs
  1241. Resources are identified using URIs that follow this format:
  1242. ```
  1243. [protocol]://[host]/[path]
  1244. ```
  1245. For example:
  1246. * `file:///home/user/documents/report.pdf`
  1247. * `postgres://database/customers/schema`
  1248. * `screen://localhost/display1`
  1249. The protocol and path structure is defined by the MCP server implementation. Servers can define their own custom URI schemes.
  1250. ## Resource types
  1251. Resources can contain two types of content:
  1252. ### Text resources
  1253. Text resources contain UTF-8 encoded text data. These are suitable for:
  1254. * Source code
  1255. * Configuration files
  1256. * Log files
  1257. * JSON/XML data
  1258. * Plain text
  1259. ### Binary resources
  1260. Binary resources contain raw binary data encoded in base64. These are suitable for:
  1261. * Images
  1262. * PDFs
  1263. * Audio files
  1264. * Video files
  1265. * Other non-text formats
  1266. ## Resource discovery
  1267. Clients can discover available resources through two main methods:
  1268. ### Direct resources
  1269. Servers expose a list of concrete resources via the `resources/list` endpoint. Each resource includes:
  1270. ```typescript
  1271. {
  1272. uri: string; // Unique identifier for the resource
  1273. name: string; // Human-readable name
  1274. description?: string; // Optional description
  1275. mimeType?: string; // Optional MIME type
  1276. size?: number; // Optional size in bytes
  1277. }
  1278. ```
  1279. ### Resource templates
  1280. For dynamic resources, servers can expose [URI templates](https://datatracker.ietf.org/doc/html/rfc6570) that clients can use to construct valid resource URIs:
  1281. ```typescript
  1282. {
  1283. uriTemplate: string; // URI template following RFC 6570
  1284. name: string; // Human-readable name for this type
  1285. description?: string; // Optional description
  1286. mimeType?: string; // Optional MIME type for all matching resources
  1287. }
  1288. ```
  1289. ## Reading resources
  1290. To read a resource, clients make a `resources/read` request with the resource URI.
  1291. The server responds with a list of resource contents:
  1292. ```typescript
  1293. {
  1294. contents: [
  1295. {
  1296. uri: string; // The URI of the resource
  1297. mimeType?: string; // Optional MIME type
  1298. // One of:
  1299. text?: string; // For text resources
  1300. blob?: string; // For binary resources (base64 encoded)
  1301. }
  1302. ]
  1303. }
  1304. ```
  1305. <Tip>
  1306. Servers may return multiple resources in response to one `resources/read` request. This could be used, for example, to return a list of files inside a directory when the directory is read.
  1307. </Tip>
  1308. ## Resource updates
  1309. MCP supports real-time updates for resources through two mechanisms:
  1310. ### List changes
  1311. Servers can notify clients when their list of available resources changes via the `notifications/resources/list_changed` notification.
  1312. ### Content changes
  1313. Clients can subscribe to updates for specific resources:
  1314. 1. Client sends `resources/subscribe` with resource URI
  1315. 2. Server sends `notifications/resources/updated` when the resource changes
  1316. 3. Client can fetch latest content with `resources/read`
  1317. 4. Client can unsubscribe with `resources/unsubscribe`
  1318. ## Example implementation
  1319. Here's a simple example of implementing resource support in an MCP server:
  1320. <Tabs>
  1321. <Tab title="TypeScript">
  1322. ```typescript
  1323. const server = new Server({
  1324. name: "example-server",
  1325. version: "1.0.0"
  1326. }, {
  1327. capabilities: {
  1328. resources: {}
  1329. }
  1330. });
  1331. // List available resources
  1332. server.setRequestHandler(ListResourcesRequestSchema, async () => {
  1333. return {
  1334. resources: [
  1335. {
  1336. uri: "file:///logs/app.log",
  1337. name: "Application Logs",
  1338. mimeType: "text/plain"
  1339. }
  1340. ]
  1341. };
  1342. });
  1343. // Read resource contents
  1344. server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
  1345. const uri = request.params.uri;
  1346. if (uri === "file:///logs/app.log") {
  1347. const logContents = await readLogFile();
  1348. return {
  1349. contents: [
  1350. {
  1351. uri,
  1352. mimeType: "text/plain",
  1353. text: logContents
  1354. }
  1355. ]
  1356. };
  1357. }
  1358. throw new Error("Resource not found");
  1359. });
  1360. ```
  1361. </Tab>
  1362. <Tab title="Python">
  1363. ```python
  1364. app = Server("example-server")
  1365. @app.list_resources()
  1366. async def list_resources() -> list[types.Resource]:
  1367. return [
  1368. types.Resource(
  1369. uri="file:///logs/app.log",
  1370. name="Application Logs",
  1371. mimeType="text/plain"
  1372. )
  1373. ]
  1374. @app.read_resource()
  1375. async def read_resource(uri: AnyUrl) -> str:
  1376. if str(uri) == "file:///logs/app.log":
  1377. log_contents = await read_log_file()
  1378. return log_contents
  1379. raise ValueError("Resource not found")
  1380. # Start server
  1381. async with stdio_server() as streams:
  1382. await app.run(
  1383. streams[0],
  1384. streams[1],
  1385. app.create_initialization_options()
  1386. )
  1387. ```
  1388. </Tab>
  1389. </Tabs>
  1390. ## Best practices
  1391. When implementing resource support:
  1392. 1. Use clear, descriptive resource names and URIs
  1393. 2. Include helpful descriptions to guide LLM understanding
  1394. 3. Set appropriate MIME types when known
  1395. 4. Implement resource templates for dynamic content
  1396. 5. Use subscriptions for frequently changing resources
  1397. 6. Handle errors gracefully with clear error messages
  1398. 7. Consider pagination for large resource lists
  1399. 8. Cache resource contents when appropriate
  1400. 9. Validate URIs before processing
  1401. 10. Document your custom URI schemes
  1402. ## Security considerations
  1403. When exposing resources:
  1404. * Validate all resource URIs
  1405. * Implement appropriate access controls
  1406. * Sanitize file paths to prevent directory traversal
  1407. * Be cautious with binary data handling
  1408. * Consider rate limiting for resource reads
  1409. * Audit resource access
  1410. * Encrypt sensitive data in transit
  1411. * Validate MIME types
  1412. * Implement timeouts for long-running reads
  1413. * Handle resource cleanup appropriately
  1414. # Roots
  1415. Source: https://modelcontextprotocol.io/docs/concepts/roots
  1416. Understanding roots in MCP
  1417. Roots are a concept in MCP that define the boundaries where servers can operate. They provide a way for clients to inform servers about relevant resources and their locations.
  1418. ## What are Roots?
  1419. A root is a URI that a client suggests a server should focus on. When a client connects to a server, it declares which roots the server should work with. While primarily used for filesystem paths, roots can be any valid URI including HTTP URLs.
  1420. For example, roots could be:
  1421. ```
  1422. file:///home/user/projects/myapp
  1423. https://api.example.com/v1
  1424. ```
  1425. ## Why Use Roots?
  1426. Roots serve several important purposes:
  1427. 1. **Guidance**: They inform servers about relevant resources and locations
  1428. 2. **Clarity**: Roots make it clear which resources are part of your workspace
  1429. 3. **Organization**: Multiple roots let you work with different resources simultaneously
  1430. ## How Roots Work
  1431. When a client supports roots, it:
  1432. 1. Declares the `roots` capability during connection
  1433. 2. Provides a list of suggested roots to the server
  1434. 3. Notifies the server when roots change (if supported)
  1435. While roots are informational and not strictly enforcing, servers should:
  1436. 1. Respect the provided roots
  1437. 2. Use root URIs to locate and access resources
  1438. 3. Prioritize operations within root boundaries
  1439. ## Common Use Cases
  1440. Roots are commonly used to define:
  1441. * Project directories
  1442. * Repository locations
  1443. * API endpoints
  1444. * Configuration locations
  1445. * Resource boundaries
  1446. ## Best Practices
  1447. When working with roots:
  1448. 1. Only suggest necessary resources
  1449. 2. Use clear, descriptive names for roots
  1450. 3. Monitor root accessibility
  1451. 4. Handle root changes gracefully
  1452. ## Example
  1453. Here's how a typical MCP client might expose roots:
  1454. ```json
  1455. {
  1456. "roots": [
  1457. {
  1458. "uri": "file:///home/user/projects/frontend",
  1459. "name": "Frontend Repository"
  1460. },
  1461. {
  1462. "uri": "https://api.example.com/v1",
  1463. "name": "API Endpoint"
  1464. }
  1465. ]
  1466. }
  1467. ```
  1468. This configuration suggests the server focus on both a local repository and an API endpoint while keeping them logically separated.
  1469. # Sampling
  1470. Source: https://modelcontextprotocol.io/docs/concepts/sampling
  1471. Let your servers request completions from LLMs
  1472. Sampling is a powerful MCP feature that allows servers to request LLM completions through the client, enabling sophisticated agentic behaviors while maintaining security and privacy.
  1473. <Info>
  1474. This feature of MCP is not yet supported in the Claude Desktop client.
  1475. </Info>
  1476. ## How sampling works
  1477. The sampling flow follows these steps:
  1478. 1. Server sends a `sampling/createMessage` request to the client
  1479. 2. Client reviews the request and can modify it
  1480. 3. Client samples from an LLM
  1481. 4. Client reviews the completion
  1482. 5. Client returns the result to the server
  1483. This human-in-the-loop design ensures users maintain control over what the LLM sees and generates.
  1484. ## Message format
  1485. Sampling requests use a standardized message format:
  1486. ```typescript
  1487. {
  1488. messages: [
  1489. {
  1490. role: "user" | "assistant",
  1491. content: {
  1492. type: "text" | "image",
  1493. // For text:
  1494. text?: string,
  1495. // For images:
  1496. data?: string, // base64 encoded
  1497. mimeType?: string
  1498. }
  1499. }
  1500. ],
  1501. modelPreferences?: {
  1502. hints?: [{
  1503. name?: string // Suggested model name/family
  1504. }],
  1505. costPriority?: number, // 0-1, importance of minimizing cost
  1506. speedPriority?: number, // 0-1, importance of low latency
  1507. intelligencePriority?: number // 0-1, importance of capabilities
  1508. },
  1509. systemPrompt?: string,
  1510. includeContext?: "none" | "thisServer" | "allServers",
  1511. temperature?: number,
  1512. maxTokens: number,
  1513. stopSequences?: string[],
  1514. metadata?: Record<string, unknown>
  1515. }
  1516. ```
  1517. ## Request parameters
  1518. ### Messages
  1519. The `messages` array contains the conversation history to send to the LLM. Each message has:
  1520. * `role`: Either "user" or "assistant"
  1521. * `content`: The message content, which can be:
  1522. * Text content with a `text` field
  1523. * Image content with `data` (base64) and `mimeType` fields
  1524. ### Model preferences
  1525. The `modelPreferences` object allows servers to specify their model selection preferences:
  1526. * `hints`: Array of model name suggestions that clients can use to select an appropriate model:
  1527. * `name`: String that can match full or partial model names (e.g. "claude-3", "sonnet")
  1528. * Clients may map hints to equivalent models from different providers
  1529. * Multiple hints are evaluated in preference order
  1530. * Priority values (0-1 normalized):
  1531. * `costPriority`: Importance of minimizing costs
  1532. * `speedPriority`: Importance of low latency response
  1533. * `intelligencePriority`: Importance of advanced model capabilities
  1534. Clients make the final model selection based on these preferences and their available models.
  1535. ### System prompt
  1536. An optional `systemPrompt` field allows servers to request a specific system prompt. The client may modify or ignore this.
  1537. ### Context inclusion
  1538. The `includeContext` parameter specifies what MCP context to include:
  1539. * `"none"`: No additional context
  1540. * `"thisServer"`: Include context from the requesting server
  1541. * `"allServers"`: Include context from all connected MCP servers
  1542. The client controls what context is actually included.
  1543. ### Sampling parameters
  1544. Fine-tune the LLM sampling with:
  1545. * `temperature`: Controls randomness (0.0 to 1.0)
  1546. * `maxTokens`: Maximum tokens to generate
  1547. * `stopSequences`: Array of sequences that stop generation
  1548. * `metadata`: Additional provider-specific parameters
  1549. ## Response format
  1550. The client returns a completion result:
  1551. ```typescript
  1552. {
  1553. model: string, // Name of the model used
  1554. stopReason?: "endTurn" | "stopSequence" | "maxTokens" | string,
  1555. role: "user" | "assistant",
  1556. content: {
  1557. type: "text" | "image",
  1558. text?: string,
  1559. data?: string,
  1560. mimeType?: string
  1561. }
  1562. }
  1563. ```
  1564. ## Example request
  1565. Here's an example of requesting sampling from a client:
  1566. ```json
  1567. {
  1568. "method": "sampling/createMessage",
  1569. "params": {
  1570. "messages": [
  1571. {
  1572. "role": "user",
  1573. "content": {
  1574. "type": "text",
  1575. "text": "What files are in the current directory?"
  1576. }
  1577. }
  1578. ],
  1579. "systemPrompt": "You are a helpful file system assistant.",
  1580. "includeContext": "thisServer",
  1581. "maxTokens": 100
  1582. }
  1583. }
  1584. ```
  1585. ## Best practices
  1586. When implementing sampling:
  1587. 1. Always provide clear, well-structured prompts
  1588. 2. Handle both text and image content appropriately
  1589. 3. Set reasonable token limits
  1590. 4. Include relevant context through `includeContext`
  1591. 5. Validate responses before using them
  1592. 6. Handle errors gracefully
  1593. 7. Consider rate limiting sampling requests
  1594. 8. Document expected sampling behavior
  1595. 9. Test with various model parameters
  1596. 10. Monitor sampling costs
  1597. ## Human in the loop controls
  1598. Sampling is designed with human oversight in mind:
  1599. ### For prompts
  1600. * Clients should show users the proposed prompt
  1601. * Users should be able to modify or reject prompts
  1602. * System prompts can be filtered or modified
  1603. * Context inclusion is controlled by the client
  1604. ### For completions
  1605. * Clients should show users the completion
  1606. * Users should be able to modify or reject completions
  1607. * Clients can filter or modify completions
  1608. * Users control which model is used
  1609. ## Security considerations
  1610. When implementing sampling:
  1611. * Validate all message content
  1612. * Sanitize sensitive information
  1613. * Implement appropriate rate limits
  1614. * Monitor sampling usage
  1615. * Encrypt data in transit
  1616. * Handle user data privacy
  1617. * Audit sampling requests
  1618. * Control cost exposure
  1619. * Implement timeouts
  1620. * Handle model errors gracefully
  1621. ## Common patterns
  1622. ### Agentic workflows
  1623. Sampling enables agentic patterns like:
  1624. * Reading and analyzing resources
  1625. * Making decisions based on context
  1626. * Generating structured data
  1627. * Handling multi-step tasks
  1628. * Providing interactive assistance
  1629. ### Context management
  1630. Best practices for context:
  1631. * Request minimal necessary context
  1632. * Structure context clearly
  1633. * Handle context size limits
  1634. * Update context as needed
  1635. * Clean up stale context
  1636. ### Error handling
  1637. Robust error handling should:
  1638. * Catch sampling failures
  1639. * Handle timeout errors
  1640. * Manage rate limits
  1641. * Validate responses
  1642. * Provide fallback behaviors
  1643. * Log errors appropriately
  1644. ## Limitations
  1645. Be aware of these limitations:
  1646. * Sampling depends on client capabilities
  1647. * Users control sampling behavior
  1648. * Context size has limits
  1649. * Rate limits may apply
  1650. * Costs should be considered
  1651. * Model availability varies
  1652. * Response times vary
  1653. * Not all content types supported
  1654. # Tools
  1655. Source: https://modelcontextprotocol.io/docs/concepts/tools
  1656. Enable LLMs to perform actions through your server
  1657. Tools are a powerful primitive in the Model Context Protocol (MCP) that enable servers to expose executable functionality to clients. Through tools, LLMs can interact with external systems, perform computations, and take actions in the real world.
  1658. <Note>
  1659. Tools are designed to be **model-controlled**, meaning that tools are exposed from servers to clients with the intention of the AI model being able to automatically invoke them (with a human in the loop to grant approval).
  1660. </Note>
  1661. ## Overview
  1662. Tools in MCP allow servers to expose executable functions that can be invoked by clients and used by LLMs to perform actions. Key aspects of tools include:
  1663. * **Discovery**: Clients can list available tools through the `tools/list` endpoint
  1664. * **Invocation**: Tools are called using the `tools/call` endpoint, where servers perform the requested operation and return results
  1665. * **Flexibility**: Tools can range from simple calculations to complex API interactions
  1666. Like [resources](/docs/concepts/resources), tools are identified by unique names and can include descriptions to guide their usage. However, unlike resources, tools represent dynamic operations that can modify state or interact with external systems.
  1667. ## Tool definition structure
  1668. Each tool is defined with the following structure:
  1669. ```typescript
  1670. {
  1671. name: string; // Unique identifier for the tool
  1672. description?: string; // Human-readable description
  1673. inputSchema: { // JSON Schema for the tool's parameters
  1674. type: "object",
  1675. properties: { ... } // Tool-specific parameters
  1676. },
  1677. annotations?: { // Optional hints about tool behavior
  1678. title?: string; // Human-readable title for the tool
  1679. readOnlyHint?: boolean; // If true, the tool does not modify its environment
  1680. destructiveHint?: boolean; // If true, the tool may perform destructive updates
  1681. idempotentHint?: boolean; // If true, repeated calls with same args have no additional effect
  1682. openWorldHint?: boolean; // If true, tool interacts with external entities
  1683. }
  1684. }
  1685. ```
  1686. ## Implementing tools
  1687. Here's an example of implementing a basic tool in an MCP server:
  1688. <Tabs>
  1689. <Tab title="TypeScript">
  1690. ```typescript
  1691. const server = new Server({
  1692. name: "example-server",
  1693. version: "1.0.0"
  1694. }, {
  1695. capabilities: {
  1696. tools: {}
  1697. }
  1698. });
  1699. // Define available tools
  1700. server.setRequestHandler(ListToolsRequestSchema, async () => {
  1701. return {
  1702. tools: [{
  1703. name: "calculate_sum",
  1704. description: "Add two numbers together",
  1705. inputSchema: {
  1706. type: "object",
  1707. properties: {
  1708. a: { type: "number" },
  1709. b: { type: "number" }
  1710. },
  1711. required: ["a", "b"]
  1712. }
  1713. }]
  1714. };
  1715. });
  1716. // Handle tool execution
  1717. server.setRequestHandler(CallToolRequestSchema, async (request) => {
  1718. if (request.params.name === "calculate_sum") {
  1719. const { a, b } = request.params.arguments;
  1720. return {
  1721. content: [
  1722. {
  1723. type: "text",
  1724. text: String(a + b)
  1725. }
  1726. ]
  1727. };
  1728. }
  1729. throw new Error("Tool not found");
  1730. });
  1731. ```
  1732. </Tab>
  1733. <Tab title="Python">
  1734. ```python
  1735. app = Server("example-server")
  1736. @app.list_tools()
  1737. async def list_tools() -> list[types.Tool]:
  1738. return [
  1739. types.Tool(
  1740. name="calculate_sum",
  1741. description="Add two numbers together",
  1742. inputSchema={
  1743. "type": "object",
  1744. "properties": {
  1745. "a": {"type": "number"},
  1746. "b": {"type": "number"}
  1747. },
  1748. "required": ["a", "b"]
  1749. }
  1750. )
  1751. ]
  1752. @app.call_tool()
  1753. async def call_tool(
  1754. name: str,
  1755. arguments: dict
  1756. ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
  1757. if name == "calculate_sum":
  1758. a = arguments["a"]
  1759. b = arguments["b"]
  1760. result = a + b
  1761. return [types.TextContent(type="text", text=str(result))]
  1762. raise ValueError(f"Tool not found: {name}")
  1763. ```
  1764. </Tab>
  1765. </Tabs>
  1766. ## Example tool patterns
  1767. Here are some examples of types of tools that a server could provide:
  1768. ### System operations
  1769. Tools that interact with the local system:
  1770. ```typescript
  1771. {
  1772. name: "execute_command",
  1773. description: "Run a shell command",
  1774. inputSchema: {
  1775. type: "object",
  1776. properties: {
  1777. command: { type: "string" },
  1778. args: { type: "array", items: { type: "string" } }
  1779. }
  1780. }
  1781. }
  1782. ```
  1783. ### API integrations
  1784. Tools that wrap external APIs:
  1785. ```typescript
  1786. {
  1787. name: "github_create_issue",
  1788. description: "Create a GitHub issue",
  1789. inputSchema: {
  1790. type: "object",
  1791. properties: {
  1792. title: { type: "string" },
  1793. body: { type: "string" },
  1794. labels: { type: "array", items: { type: "string" } }
  1795. }
  1796. }
  1797. }
  1798. ```
  1799. ### Data processing
  1800. Tools that transform or analyze data:
  1801. ```typescript
  1802. {
  1803. name: "analyze_csv",
  1804. description: "Analyze a CSV file",
  1805. inputSchema: {
  1806. type: "object",
  1807. properties: {
  1808. filepath: { type: "string" },
  1809. operations: {
  1810. type: "array",
  1811. items: {
  1812. enum: ["sum", "average", "count"]
  1813. }
  1814. }
  1815. }
  1816. }
  1817. }
  1818. ```
  1819. ## Best practices
  1820. When implementing tools:
  1821. 1. Provide clear, descriptive names and descriptions
  1822. 2. Use detailed JSON Schema definitions for parameters
  1823. 3. Include examples in tool descriptions to demonstrate how the model should use them
  1824. 4. Implement proper error handling and validation
  1825. 5. Use progress reporting for long operations
  1826. 6. Keep tool operations focused and atomic
  1827. 7. Document expected return value structures
  1828. 8. Implement proper timeouts
  1829. 9. Consider rate limiting for resource-intensive operations
  1830. 10. Log tool usage for debugging and monitoring
  1831. ## Security considerations
  1832. When exposing tools:
  1833. ### Input validation
  1834. * Validate all parameters against the schema
  1835. * Sanitize file paths and system commands
  1836. * Validate URLs and external identifiers
  1837. * Check parameter sizes and ranges
  1838. * Prevent command injection
  1839. ### Access control
  1840. * Implement authentication where needed
  1841. * Use appropriate authorization checks
  1842. * Audit tool usage
  1843. * Rate limit requests
  1844. * Monitor for abuse
  1845. ### Error handling
  1846. * Don't expose internal errors to clients
  1847. * Log security-relevant errors
  1848. * Handle timeouts appropriately
  1849. * Clean up resources after errors
  1850. * Validate return values
  1851. ## Tool discovery and updates
  1852. MCP supports dynamic tool discovery:
  1853. 1. Clients can list available tools at any time
  1854. 2. Servers can notify clients when tools change using `notifications/tools/list_changed`
  1855. 3. Tools can be added or removed during runtime
  1856. 4. Tool definitions can be updated (though this should be done carefully)
  1857. ## Error handling
  1858. Tool errors should be reported within the result object, not as MCP protocol-level errors. This allows the LLM to see and potentially handle the error. When a tool encounters an error:
  1859. 1. Set `isError` to `true` in the result
  1860. 2. Include error details in the `content` array
  1861. Here's an example of proper error handling for tools:
  1862. <Tabs>
  1863. <Tab title="TypeScript">
  1864. ```typescript
  1865. try {
  1866. // Tool operation
  1867. const result = performOperation();
  1868. return {
  1869. content: [
  1870. {
  1871. type: "text",
  1872. text: `Operation successful: ${result}`
  1873. }
  1874. ]
  1875. };
  1876. } catch (error) {
  1877. return {
  1878. isError: true,
  1879. content: [
  1880. {
  1881. type: "text",
  1882. text: `Error: ${error.message}`
  1883. }
  1884. ]
  1885. };
  1886. }
  1887. ```
  1888. </Tab>
  1889. <Tab title="Python">
  1890. ```python
  1891. try:
  1892. # Tool operation
  1893. result = perform_operation()
  1894. return types.CallToolResult(
  1895. content=[
  1896. types.TextContent(
  1897. type="text",
  1898. text=f"Operation successful: {result}"
  1899. )
  1900. ]
  1901. )
  1902. except Exception as error:
  1903. return types.CallToolResult(
  1904. isError=True,
  1905. content=[
  1906. types.TextContent(
  1907. type="text",
  1908. text=f"Error: {str(error)}"
  1909. )
  1910. ]
  1911. )
  1912. ```
  1913. </Tab>
  1914. </Tabs>
  1915. This approach allows the LLM to see that an error occurred and potentially take corrective action or request human intervention.
  1916. ## Tool annotations
  1917. Tool annotations provide additional metadata about a tool's behavior, helping clients understand how to present and manage tools. These annotations are hints that describe the nature and impact of a tool, but should not be relied upon for security decisions.
  1918. ### Purpose of tool annotations
  1919. Tool annotations serve several key purposes:
  1920. 1. Provide UX-specific information without affecting model context
  1921. 2. Help clients categorize and present tools appropriately
  1922. 3. Convey information about a tool's potential side effects
  1923. 4. Assist in developing intuitive interfaces for tool approval
  1924. ### Available tool annotations
  1925. The MCP specification defines the following annotations for tools:
  1926. | Annotation | Type | Default | Description |
  1927. | ----------------- | ------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------ |
  1928. | `title` | string | - | A human-readable title for the tool, useful for UI display |
  1929. | `readOnlyHint` | boolean | false | If true, indicates the tool does not modify its environment |
  1930. | `destructiveHint` | boolean | true | If true, the tool may perform destructive updates (only meaningful when `readOnlyHint` is false) |
  1931. | `idempotentHint` | boolean | false | If true, calling the tool repeatedly with the same arguments has no additional effect (only meaningful when `readOnlyHint` is false) |
  1932. | `openWorldHint` | boolean | true | If true, the tool may interact with an "open world" of external entities |
  1933. ### Example usage
  1934. Here's how to define tools with annotations for different scenarios:
  1935. ```typescript
  1936. // A read-only search tool
  1937. {
  1938. name: "web_search",
  1939. description: "Search the web for information",
  1940. inputSchema: {
  1941. type: "object",
  1942. properties: {
  1943. query: { type: "string" }
  1944. },
  1945. required: ["query"]
  1946. },
  1947. annotations: {
  1948. title: "Web Search",
  1949. readOnlyHint: true,
  1950. openWorldHint: true
  1951. }
  1952. }
  1953. // A destructive file deletion tool
  1954. {
  1955. name: "delete_file",
  1956. description: "Delete a file from the filesystem",
  1957. inputSchema: {
  1958. type: "object",
  1959. properties: {
  1960. path: { type: "string" }
  1961. },
  1962. required: ["path"]
  1963. },
  1964. annotations: {
  1965. title: "Delete File",
  1966. readOnlyHint: false,
  1967. destructiveHint: true,
  1968. idempotentHint: true,
  1969. openWorldHint: false
  1970. }
  1971. }
  1972. // A non-destructive database record creation tool
  1973. {
  1974. name: "create_record",
  1975. description: "Create a new record in the database",
  1976. inputSchema: {
  1977. type: "object",
  1978. properties: {
  1979. table: { type: "string" },
  1980. data: { type: "object" }
  1981. },
  1982. required: ["table", "data"]
  1983. },
  1984. annotations: {
  1985. title: "Create Database Record",
  1986. readOnlyHint: false,
  1987. destructiveHint: false,
  1988. idempotentHint: false,
  1989. openWorldHint: false
  1990. }
  1991. }
  1992. ```
  1993. ### Integrating annotations in server implementation
  1994. <Tabs>
  1995. <Tab title="TypeScript">
  1996. ```typescript
  1997. server.setRequestHandler(ListToolsRequestSchema, async () => {
  1998. return {
  1999. tools: [{
  2000. name: "calculate_sum",
  2001. description: "Add two numbers together",
  2002. inputSchema: {
  2003. type: "object",
  2004. properties: {
  2005. a: { type: "number" },
  2006. b: { type: "number" }
  2007. },
  2008. required: ["a", "b"]
  2009. },
  2010. annotations: {
  2011. title: "Calculate Sum",
  2012. readOnlyHint: true,
  2013. openWorldHint: false
  2014. }
  2015. }]
  2016. };
  2017. });
  2018. ```
  2019. </Tab>
  2020. <Tab title="Python">
  2021. ```python
  2022. from mcp.server.fastmcp import FastMCP
  2023. mcp = FastMCP("example-server")
  2024. @mcp.tool(
  2025. annotations={
  2026. "title": "Calculate Sum",
  2027. "readOnlyHint": True,
  2028. "openWorldHint": False
  2029. }
  2030. )
  2031. async def calculate_sum(a: float, b: float) -> str:
  2032. """Add two numbers together.
  2033. Args:
  2034. a: First number to add
  2035. b: Second number to add
  2036. """
  2037. result = a + b
  2038. return str(result)
  2039. ```
  2040. </Tab>
  2041. </Tabs>
  2042. ### Best practices for tool annotations
  2043. 1. **Be accurate about side effects**: Clearly indicate whether a tool modifies its environment and whether those modifications are destructive.
  2044. 2. **Use descriptive titles**: Provide human-friendly titles that clearly describe the tool's purpose.
  2045. 3. **Indicate idempotency properly**: Mark tools as idempotent only if repeated calls with the same arguments truly have no additional effect.
  2046. 4. **Set appropriate open/closed world hints**: Indicate whether a tool interacts with a closed system (like a database) or an open system (like the web).
  2047. 5. **Remember annotations are hints**: All properties in ToolAnnotations are hints and not guaranteed to provide a faithful description of tool behavior. Clients should never make security-critical decisions based solely on annotations.
  2048. ## Testing tools
  2049. A comprehensive testing strategy for MCP tools should cover:
  2050. * **Functional testing**: Verify tools execute correctly with valid inputs and handle invalid inputs appropriately
  2051. * **Integration testing**: Test tool interaction with external systems using both real and mocked dependencies
  2052. * **Security testing**: Validate authentication, authorization, input sanitization, and rate limiting
  2053. * **Performance testing**: Check behavior under load, timeout handling, and resource cleanup
  2054. * **Error handling**: Ensure tools properly report errors through the MCP protocol and clean up resources
  2055. # Transports
  2056. Source: https://modelcontextprotocol.io/docs/concepts/transports
  2057. Learn about MCP's communication mechanisms
  2058. Transports in the Model Context Protocol (MCP) provide the foundation for communication between clients and servers. A transport handles the underlying mechanics of how messages are sent and received.
  2059. ## Message Format
  2060. MCP uses [JSON-RPC](https://www.jsonrpc.org/) 2.0 as its wire format. The transport layer is responsible for converting MCP protocol messages into JSON-RPC format for transmission and converting received JSON-RPC messages back into MCP protocol messages.
  2061. There are three types of JSON-RPC messages used:
  2062. ### Requests
  2063. ```typescript
  2064. {
  2065. jsonrpc: "2.0",
  2066. id: number | string,
  2067. method: string,
  2068. params?: object
  2069. }
  2070. ```
  2071. ### Responses
  2072. ```typescript
  2073. {
  2074. jsonrpc: "2.0",
  2075. id: number | string,
  2076. result?: object,
  2077. error?: {
  2078. code: number,
  2079. message: string,
  2080. data?: unknown
  2081. }
  2082. }
  2083. ```
  2084. ### Notifications
  2085. ```typescript
  2086. {
  2087. jsonrpc: "2.0",
  2088. method: string,
  2089. params?: object
  2090. }
  2091. ```
  2092. ## Built-in Transport Types
  2093. MCP currently defines two standard transport mechanisms:
  2094. ### Standard Input/Output (stdio)
  2095. The stdio transport enables communication through standard input and output streams. This is particularly useful for local integrations and command-line tools.
  2096. Use stdio when:
  2097. * Building command-line tools
  2098. * Implementing local integrations
  2099. * Needing simple process communication
  2100. * Working with shell scripts
  2101. <Tabs>
  2102. <Tab title="TypeScript (Server)">
  2103. ```typescript
  2104. const server = new Server({
  2105. name: "example-server",
  2106. version: "1.0.0"
  2107. }, {
  2108. capabilities: {}
  2109. });
  2110. const transport = new StdioServerTransport();
  2111. await server.connect(transport);
  2112. ```
  2113. </Tab>
  2114. <Tab title="TypeScript (Client)">
  2115. ```typescript
  2116. const client = new Client({
  2117. name: "example-client",
  2118. version: "1.0.0"
  2119. }, {
  2120. capabilities: {}
  2121. });
  2122. const transport = new StdioClientTransport({
  2123. command: "./server",
  2124. args: ["--option", "value"]
  2125. });
  2126. await client.connect(transport);
  2127. ```
  2128. </Tab>
  2129. <Tab title="Python (Server)">
  2130. ```python
  2131. app = Server("example-server")
  2132. async with stdio_server() as streams:
  2133. await app.run(
  2134. streams[0],
  2135. streams[1],
  2136. app.create_initialization_options()
  2137. )
  2138. ```
  2139. </Tab>
  2140. <Tab title="Python (Client)">
  2141. ```python
  2142. params = StdioServerParameters(
  2143. command="./server",
  2144. args=["--option", "value"]
  2145. )
  2146. async with stdio_client(params) as streams:
  2147. async with ClientSession(streams[0], streams[1]) as session:
  2148. await session.initialize()
  2149. ```
  2150. </Tab>
  2151. </Tabs>
  2152. ### Streamable HTTP
  2153. The Streamable HTTP transport uses HTTP POST requests for client-to-server communication and optional Server-Sent Events (SSE) streams for server-to-client communication.
  2154. Use Streamable HTTP when:
  2155. * Building web-based integrations
  2156. * Needing client-server communication over HTTP
  2157. * Requiring stateful sessions
  2158. * Supporting multiple concurrent clients
  2159. * Implementing resumable connections
  2160. #### How it Works
  2161. 1. **Client-to-Server Communication**: Every JSON-RPC message from client to server is sent as a new HTTP POST request to the MCP endpoint
  2162. 2. **Server Responses**: The server can respond either with:
  2163. * A single JSON response (`Content-Type: application/json`)
  2164. * An SSE stream (`Content-Type: text/event-stream`) for multiple messages
  2165. 3. **Server-to-Client Communication**: Servers can send requests/notifications to clients via:
  2166. * SSE streams initiated by client requests
  2167. * SSE streams from HTTP GET requests to the MCP endpoint
  2168. <Tabs>
  2169. <Tab title="TypeScript (Server)">
  2170. ```typescript
  2171. import express from "express";
  2172. const app = express();
  2173. const server = new Server({
  2174. name: "example-server",
  2175. version: "1.0.0"
  2176. }, {
  2177. capabilities: {}
  2178. });
  2179. // MCP endpoint handles both POST and GET
  2180. app.post("/mcp", async (req, res) => {
  2181. // Handle JSON-RPC request
  2182. const response = await server.handleRequest(req.body);
  2183. // Return single response or SSE stream
  2184. if (needsStreaming) {
  2185. res.setHeader("Content-Type", "text/event-stream");
  2186. // Send SSE events...
  2187. } else {
  2188. res.json(response);
  2189. }
  2190. });
  2191. app.get("/mcp", (req, res) => {
  2192. // Optional: Support server-initiated SSE streams
  2193. res.setHeader("Content-Type", "text/event-stream");
  2194. // Send server notifications/requests...
  2195. });
  2196. app.listen(3000);
  2197. ```
  2198. </Tab>
  2199. <Tab title="TypeScript (Client)">
  2200. ```typescript
  2201. const client = new Client({
  2202. name: "example-client",
  2203. version: "1.0.0"
  2204. }, {
  2205. capabilities: {}
  2206. });
  2207. const transport = new HttpClientTransport(
  2208. new URL("http://localhost:3000/mcp")
  2209. );
  2210. await client.connect(transport);
  2211. ```
  2212. </Tab>
  2213. <Tab title="Python (Server)">
  2214. ```python
  2215. from mcp.server.http import HttpServerTransport
  2216. from starlette.applications import Starlette
  2217. from starlette.routing import Route
  2218. app = Server("example-server")
  2219. async def handle_mcp(scope, receive, send):
  2220. if scope["method"] == "POST":
  2221. # Handle JSON-RPC request
  2222. response = await app.handle_request(request_body)
  2223. if needs_streaming:
  2224. # Return SSE stream
  2225. await send_sse_response(send, response)
  2226. else:
  2227. # Return JSON response
  2228. await send_json_response(send, response)
  2229. elif scope["method"] == "GET":
  2230. # Optional: Support server-initiated SSE streams
  2231. await send_sse_stream(send)
  2232. starlette_app = Starlette(
  2233. routes=[
  2234. Route("/mcp", endpoint=handle_mcp, methods=["POST", "GET"]),
  2235. ]
  2236. )
  2237. ```
  2238. </Tab>
  2239. <Tab title="Python (Client)">
  2240. ```python
  2241. async with http_client("http://localhost:8000/mcp") as transport:
  2242. async with ClientSession(transport[0], transport[1]) as session:
  2243. await session.initialize()
  2244. ```
  2245. </Tab>
  2246. </Tabs>
  2247. #### Session Management
  2248. Streamable HTTP supports stateful sessions to maintain context across multiple requests:
  2249. 1. **Session Initialization**: Servers may assign a session ID during initialization by including it in an `Mcp-Session-Id` header
  2250. 2. **Session Persistence**: Clients must include the session ID in all subsequent requests using the `Mcp-Session-Id` header
  2251. 3. **Session Termination**: Sessions can be explicitly terminated by sending an HTTP DELETE request with the session ID
  2252. Example session flow:
  2253. ```typescript
  2254. // Server assigns session ID during initialization
  2255. app.post("/mcp", (req, res) => {
  2256. if (req.body.method === "initialize") {
  2257. const sessionId = generateSecureId();
  2258. res.setHeader("Mcp-Session-Id", sessionId);
  2259. // Store session state...
  2260. }
  2261. // Handle request...
  2262. });
  2263. // Client includes session ID in subsequent requests
  2264. fetch("/mcp", {
  2265. method: "POST",
  2266. headers: {
  2267. "Content-Type": "application/json",
  2268. "Mcp-Session-Id": sessionId,
  2269. },
  2270. body: JSON.stringify(request),
  2271. });
  2272. ```
  2273. #### Resumability and Redelivery
  2274. To support resuming broken connections, Streamable HTTP provides:
  2275. 1. **Event IDs**: Servers can attach unique IDs to SSE events for tracking
  2276. 2. **Resume from Last Event**: Clients can resume by sending the `Last-Event-ID` header
  2277. 3. **Message Replay**: Servers can replay missed messages from the disconnection point
  2278. This ensures reliable message delivery even with unstable network connections.
  2279. #### Security Considerations
  2280. When implementing Streamable HTTP transport, follow these security best practices:
  2281. 1. **Validate Origin Headers**: Always validate the `Origin` header on all incoming connections to prevent DNS rebinding attacks
  2282. 2. **Bind to Localhost**: When running locally, bind only to localhost (127.0.0.1) rather than all network interfaces (0.0.0.0)
  2283. 3. **Implement Authentication**: Use proper authentication for all connections
  2284. 4. **Use HTTPS**: Always use TLS/HTTPS for production deployments
  2285. 5. **Validate Session IDs**: Ensure session IDs are cryptographically secure and properly validated
  2286. Without these protections, attackers could use DNS rebinding to interact with local MCP servers from remote websites.
  2287. ### Server-Sent Events (SSE) - Deprecated
  2288. <Note>
  2289. SSE as a standalone transport is deprecated as of protocol version 2024-11-05.
  2290. It has been replaced by Streamable HTTP, which incorporates SSE as an optional
  2291. streaming mechanism. For backwards compatibility information, see the
  2292. [backwards compatibility](#backwards-compatibility) section below.
  2293. </Note>
  2294. The legacy SSE transport enabled server-to-client streaming with HTTP POST requests for client-to-server communication.
  2295. Previously used when:
  2296. * Only server-to-client streaming is needed
  2297. * Working with restricted networks
  2298. * Implementing simple updates
  2299. #### Legacy Security Considerations
  2300. The deprecated SSE transport had similar security considerations to Streamable HTTP, particularly regarding DNS rebinding attacks. These same protections should be applied when using SSE streams within the Streamable HTTP transport.
  2301. <Tabs>
  2302. <Tab title="TypeScript (Server)">
  2303. ```typescript
  2304. import express from "express";
  2305. const app = express();
  2306. const server = new Server({
  2307. name: "example-server",
  2308. version: "1.0.0"
  2309. }, {
  2310. capabilities: {}
  2311. });
  2312. let transport: SSEServerTransport | null = null;
  2313. app.get("/sse", (req, res) => {
  2314. transport = new SSEServerTransport("/messages", res);
  2315. server.connect(transport);
  2316. });
  2317. app.post("/messages", (req, res) => {
  2318. if (transport) {
  2319. transport.handlePostMessage(req, res);
  2320. }
  2321. });
  2322. app.listen(3000);
  2323. ```
  2324. </Tab>
  2325. <Tab title="TypeScript (Client)">
  2326. ```typescript
  2327. const client = new Client({
  2328. name: "example-client",
  2329. version: "1.0.0"
  2330. }, {
  2331. capabilities: {}
  2332. });
  2333. const transport = new SSEClientTransport(
  2334. new URL("http://localhost:3000/sse")
  2335. );
  2336. await client.connect(transport);
  2337. ```
  2338. </Tab>
  2339. <Tab title="Python (Server)">
  2340. ```python
  2341. from mcp.server.sse import SseServerTransport
  2342. from starlette.applications import Starlette
  2343. from starlette.routing import Route
  2344. app = Server("example-server")
  2345. sse = SseServerTransport("/messages")
  2346. async def handle_sse(scope, receive, send):
  2347. async with sse.connect_sse(scope, receive, send) as streams:
  2348. await app.run(streams[0], streams[1], app.create_initialization_options())
  2349. async def handle_messages(scope, receive, send):
  2350. await sse.handle_post_message(scope, receive, send)
  2351. starlette_app = Starlette(
  2352. routes=[
  2353. Route("/sse", endpoint=handle_sse),
  2354. Route("/messages", endpoint=handle_messages, methods=["POST"]),
  2355. ]
  2356. )
  2357. ```
  2358. </Tab>
  2359. <Tab title="Python (Client)">
  2360. ```python
  2361. async with sse_client("http://localhost:8000/sse") as streams:
  2362. async with ClientSession(streams[0], streams[1]) as session:
  2363. await session.initialize()
  2364. ```
  2365. </Tab>
  2366. </Tabs>
  2367. ## Custom Transports
  2368. MCP makes it easy to implement custom transports for specific needs. Any transport implementation just needs to conform to the Transport interface:
  2369. You can implement custom transports for:
  2370. * Custom network protocols
  2371. * Specialized communication channels
  2372. * Integration with existing systems
  2373. * Performance optimization
  2374. <Tabs>
  2375. <Tab title="TypeScript">
  2376. ```typescript
  2377. interface Transport {
  2378. // Start processing messages
  2379. start(): Promise<void>;
  2380. // Send a JSON-RPC message
  2381. send(message: JSONRPCMessage): Promise<void>;
  2382. // Close the connection
  2383. close(): Promise<void>;
  2384. // Callbacks
  2385. onclose?: () => void;
  2386. onerror?: (error: Error) => void;
  2387. onmessage?: (message: JSONRPCMessage) => void;
  2388. }
  2389. ```
  2390. </Tab>
  2391. <Tab title="Python">
  2392. Note that while MCP Servers are often implemented with asyncio, we recommend
  2393. implementing low-level interfaces like transports with `anyio` for wider compatibility.
  2394. ```python
  2395. @contextmanager
  2396. async def create_transport(
  2397. read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception],
  2398. write_stream: MemoryObjectSendStream[JSONRPCMessage]
  2399. ):
  2400. """
  2401. Transport interface for MCP.
  2402. Args:
  2403. read_stream: Stream to read incoming messages from
  2404. write_stream: Stream to write outgoing messages to
  2405. """
  2406. async with anyio.create_task_group() as tg:
  2407. try:
  2408. # Start processing messages
  2409. tg.start_soon(lambda: process_messages(read_stream))
  2410. # Send messages
  2411. async with write_stream:
  2412. yield write_stream
  2413. except Exception as exc:
  2414. # Handle errors
  2415. raise exc
  2416. finally:
  2417. # Clean up
  2418. tg.cancel_scope.cancel()
  2419. await write_stream.aclose()
  2420. await read_stream.aclose()
  2421. ```
  2422. </Tab>
  2423. </Tabs>
  2424. ## Error Handling
  2425. Transport implementations should handle various error scenarios:
  2426. 1. Connection errors
  2427. 2. Message parsing errors
  2428. 3. Protocol errors
  2429. 4. Network timeouts
  2430. 5. Resource cleanup
  2431. Example error handling:
  2432. <Tabs>
  2433. <Tab title="TypeScript">
  2434. ```typescript
  2435. class ExampleTransport implements Transport {
  2436. async start() {
  2437. try {
  2438. // Connection logic
  2439. } catch (error) {
  2440. this.onerror?.(new Error(`Failed to connect: ${error}`));
  2441. throw error;
  2442. }
  2443. }
  2444. async send(message: JSONRPCMessage) {
  2445. try {
  2446. // Sending logic
  2447. } catch (error) {
  2448. this.onerror?.(new Error(`Failed to send message: ${error}`));
  2449. throw error;
  2450. }
  2451. }
  2452. }
  2453. ```
  2454. </Tab>
  2455. <Tab title="Python">
  2456. Note that while MCP Servers are often implemented with asyncio, we recommend
  2457. implementing low-level interfaces like transports with `anyio` for wider compatibility.
  2458. ```python
  2459. @contextmanager
  2460. async def example_transport(scope: Scope, receive: Receive, send: Send):
  2461. try:
  2462. # Create streams for bidirectional communication
  2463. read_stream_writer, read_stream = anyio.create_memory_object_stream(0)
  2464. write_stream, write_stream_reader = anyio.create_memory_object_stream(0)
  2465. async def message_handler():
  2466. try:
  2467. async with read_stream_writer:
  2468. # Message handling logic
  2469. pass
  2470. except Exception as exc:
  2471. logger.error(f"Failed to handle message: {exc}")
  2472. raise exc
  2473. async with anyio.create_task_group() as tg:
  2474. tg.start_soon(message_handler)
  2475. try:
  2476. # Yield streams for communication
  2477. yield read_stream, write_stream
  2478. except Exception as exc:
  2479. logger.error(f"Transport error: {exc}")
  2480. raise exc
  2481. finally:
  2482. tg.cancel_scope.cancel()
  2483. await write_stream.aclose()
  2484. await read_stream.aclose()
  2485. except Exception as exc:
  2486. logger.error(f"Failed to initialize transport: {exc}")
  2487. raise exc
  2488. ```
  2489. </Tab>
  2490. </Tabs>
  2491. ## Best Practices
  2492. When implementing or using MCP transport:
  2493. 1. Handle connection lifecycle properly
  2494. 2. Implement proper error handling
  2495. 3. Clean up resources on connection close
  2496. 4. Use appropriate timeouts
  2497. 5. Validate messages before sending
  2498. 6. Log transport events for debugging
  2499. 7. Implement reconnection logic when appropriate
  2500. 8. Handle backpressure in message queues
  2501. 9. Monitor connection health
  2502. 10. Implement proper security measures
  2503. ## Security Considerations
  2504. When implementing transport:
  2505. ### Authentication and Authorization
  2506. * Implement proper authentication mechanisms
  2507. * Validate client credentials
  2508. * Use secure token handling
  2509. * Implement authorization checks
  2510. ### Data Security
  2511. * Use TLS for network transport
  2512. * Encrypt sensitive data
  2513. * Validate message integrity
  2514. * Implement message size limits
  2515. * Sanitize input data
  2516. ### Network Security
  2517. * Implement rate limiting
  2518. * Use appropriate timeouts
  2519. * Handle denial of service scenarios
  2520. * Monitor for unusual patterns
  2521. * Implement proper firewall rules
  2522. * For HTTP-based transports (including Streamable HTTP), validate Origin headers to prevent DNS rebinding attacks
  2523. * For local servers, bind only to localhost (127.0.0.1) instead of all interfaces (0.0.0.0)
  2524. ## Debugging Transport
  2525. Tips for debugging transport issues:
  2526. 1. Enable debug logging
  2527. 2. Monitor message flow
  2528. 3. Check connection states
  2529. 4. Validate message formats
  2530. 5. Test error scenarios
  2531. 6. Use network analysis tools
  2532. 7. Implement health checks
  2533. 8. Monitor resource usage
  2534. 9. Test edge cases
  2535. 10. Use proper error tracking
  2536. ## Backwards Compatibility
  2537. To maintain compatibility between different protocol versions:
  2538. ### For Servers Supporting Older Clients
  2539. Servers wanting to support clients using the deprecated HTTP+SSE transport should:
  2540. 1. Host both the old SSE and POST endpoints alongside the new MCP endpoint
  2541. 2. Handle initialization requests on both endpoints
  2542. 3. Maintain separate handling logic for each transport type
  2543. ### For Clients Supporting Older Servers
  2544. Clients wanting to support servers using the deprecated transport should:
  2545. 1. Accept server URLs that may use either transport
  2546. 2. Attempt to POST an `InitializeRequest` with proper `Accept` headers:
  2547. * If successful, use Streamable HTTP transport
  2548. * If it fails with 4xx status, fall back to legacy SSE transport
  2549. 3. Issue a GET request expecting an SSE stream with `endpoint` event for legacy servers
  2550. Example compatibility detection:
  2551. ```typescript
  2552. async function detectTransport(serverUrl: string): Promise<TransportType> {
  2553. try {
  2554. // Try Streamable HTTP first
  2555. const response = await fetch(serverUrl, {
  2556. method: "POST",
  2557. headers: {
  2558. "Content-Type": "application/json",
  2559. Accept: "application/json, text/event-stream",
  2560. },
  2561. body: JSON.stringify({
  2562. jsonrpc: "2.0",
  2563. method: "initialize",
  2564. params: {
  2565. /* ... */
  2566. },
  2567. }),
  2568. });
  2569. if (response.ok) {
  2570. return "streamable-http";
  2571. }
  2572. } catch (error) {
  2573. // Fall back to legacy SSE
  2574. const sseResponse = await fetch(serverUrl, {
  2575. method: "GET",
  2576. headers: { Accept: "text/event-stream" },
  2577. });
  2578. if (sseResponse.ok) {
  2579. return "legacy-sse";
  2580. }
  2581. }
  2582. throw new Error("Unsupported transport");
  2583. }
  2584. ```
  2585. # Debugging
  2586. Source: https://modelcontextprotocol.io/docs/tools/debugging
  2587. A comprehensive guide to debugging Model Context Protocol (MCP) integrations
  2588. Effective debugging is essential when developing MCP servers or integrating them with applications. This guide covers the debugging tools and approaches available in the MCP ecosystem.
  2589. <Info>
  2590. This guide is for macOS. Guides for other platforms are coming soon.
  2591. </Info>
  2592. ## Debugging tools overview
  2593. MCP provides several tools for debugging at different levels:
  2594. 1. **MCP Inspector**
  2595. * Interactive debugging interface
  2596. * Direct server testing
  2597. * See the [Inspector guide](/docs/tools/inspector) for details
  2598. 2. **Claude Desktop Developer Tools**
  2599. * Integration testing
  2600. * Log collection
  2601. * Chrome DevTools integration
  2602. 3. **Server Logging**
  2603. * Custom logging implementations
  2604. * Error tracking
  2605. * Performance monitoring
  2606. ## Debugging in Claude Desktop
  2607. ### Checking server status
  2608. The Claude.app interface provides basic server status information:
  2609. 1. Click the <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-plug-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon to view:
  2610. * Connected servers
  2611. * Available prompts and resources
  2612. 2. Click the "Search and tools" <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-slider.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon to view:
  2613. * Tools made available to the model
  2614. ### Viewing logs
  2615. Review detailed MCP logs from Claude Desktop:
  2616. ```bash
  2617. # Follow logs in real-time
  2618. tail -n 20 -F ~/Library/Logs/Claude/mcp*.log
  2619. ```
  2620. The logs capture:
  2621. * Server connection events
  2622. * Configuration issues
  2623. * Runtime errors
  2624. * Message exchanges
  2625. ### Using Chrome DevTools
  2626. Access Chrome's developer tools inside Claude Desktop to investigate client-side errors:
  2627. 1. Create a `developer_settings.json` file with `allowDevTools` set to true:
  2628. ```bash
  2629. echo '{"allowDevTools": true}' > ~/Library/Application\ Support/Claude/developer_settings.json
  2630. ```
  2631. 2. Open DevTools: `Command-Option-Shift-i`
  2632. Note: You'll see two DevTools windows:
  2633. * Main content window
  2634. * App title bar window
  2635. Use the Console panel to inspect client-side errors.
  2636. Use the Network panel to inspect:
  2637. * Message payloads
  2638. * Connection timing
  2639. ## Common issues
  2640. ### Working directory
  2641. When using MCP servers with Claude Desktop:
  2642. * The working directory for servers launched via `claude_desktop_config.json` may be undefined (like `/` on macOS) since Claude Desktop could be started from anywhere
  2643. * Always use absolute paths in your configuration and `.env` files to ensure reliable operation
  2644. * For testing servers directly via command line, the working directory will be where you run the command
  2645. For example in `claude_desktop_config.json`, use:
  2646. ```json
  2647. {
  2648. "command": "npx",
  2649. "args": [
  2650. "-y",
  2651. "@modelcontextprotocol/server-filesystem",
  2652. "/Users/username/data"
  2653. ]
  2654. }
  2655. ```
  2656. Instead of relative paths like `./data`
  2657. ### Environment variables
  2658. MCP servers inherit only a subset of environment variables automatically, like `USER`, `HOME`, and `PATH`.
  2659. To override the default variables or provide your own, you can specify an `env` key in `claude_desktop_config.json`:
  2660. ```json
  2661. {
  2662. "myserver": {
  2663. "command": "mcp-server-myapp",
  2664. "env": {
  2665. "MYAPP_API_KEY": "some_key"
  2666. }
  2667. }
  2668. }
  2669. ```
  2670. ### Server initialization
  2671. Common initialization problems:
  2672. 1. **Path Issues**
  2673. * Incorrect server executable path
  2674. * Missing required files
  2675. * Permission problems
  2676. * Try using an absolute path for `command`
  2677. 2. **Configuration Errors**
  2678. * Invalid JSON syntax
  2679. * Missing required fields
  2680. * Type mismatches
  2681. 3. **Environment Problems**
  2682. * Missing environment variables
  2683. * Incorrect variable values
  2684. * Permission restrictions
  2685. ### Connection problems
  2686. When servers fail to connect:
  2687. 1. Check Claude Desktop logs
  2688. 2. Verify server process is running
  2689. 3. Test standalone with [Inspector](/docs/tools/inspector)
  2690. 4. Verify protocol compatibility
  2691. ## Implementing logging
  2692. ### Server-side logging
  2693. When building a server that uses the local stdio [transport](/docs/concepts/transports), all messages logged to stderr (standard error) will be captured by the host application (e.g., Claude Desktop) automatically.
  2694. <Warning>
  2695. Local MCP servers should not log messages to stdout (standard out), as this will interfere with protocol operation.
  2696. </Warning>
  2697. For all [transports](/docs/concepts/transports), you can also provide logging to the client by sending a log message notification:
  2698. <Tabs>
  2699. <Tab title="Python">
  2700. ```python
  2701. server.request_context.session.send_log_message(
  2702. level="info",
  2703. data="Server started successfully",
  2704. )
  2705. ```
  2706. </Tab>
  2707. <Tab title="TypeScript">
  2708. ```typescript
  2709. server.sendLoggingMessage({
  2710. level: "info",
  2711. data: "Server started successfully",
  2712. });
  2713. ```
  2714. </Tab>
  2715. </Tabs>
  2716. Important events to log:
  2717. * Initialization steps
  2718. * Resource access
  2719. * Tool execution
  2720. * Error conditions
  2721. * Performance metrics
  2722. ### Client-side logging
  2723. In client applications:
  2724. 1. Enable debug logging
  2725. 2. Monitor network traffic
  2726. 3. Track message exchanges
  2727. 4. Record error states
  2728. ## Debugging workflow
  2729. ### Development cycle
  2730. 1. Initial Development
  2731. * Use [Inspector](/docs/tools/inspector) for basic testing
  2732. * Implement core functionality
  2733. * Add logging points
  2734. 2. Integration Testing
  2735. * Test in Claude Desktop
  2736. * Monitor logs
  2737. * Check error handling
  2738. ### Testing changes
  2739. To test changes efficiently:
  2740. * **Configuration changes**: Restart Claude Desktop
  2741. * **Server code changes**: Use Command-R to reload
  2742. * **Quick iteration**: Use [Inspector](/docs/tools/inspector) during development
  2743. ## Best practices
  2744. ### Logging strategy
  2745. 1. **Structured Logging**
  2746. * Use consistent formats
  2747. * Include context
  2748. * Add timestamps
  2749. * Track request IDs
  2750. 2. **Error Handling**
  2751. * Log stack traces
  2752. * Include error context
  2753. * Track error patterns
  2754. * Monitor recovery
  2755. 3. **Performance Tracking**
  2756. * Log operation timing
  2757. * Monitor resource usage
  2758. * Track message sizes
  2759. * Measure latency
  2760. ### Security considerations
  2761. When debugging:
  2762. 1. **Sensitive Data**
  2763. * Sanitize logs
  2764. * Protect credentials
  2765. * Mask personal information
  2766. 2. **Access Control**
  2767. * Verify permissions
  2768. * Check authentication
  2769. * Monitor access patterns
  2770. ## Getting help
  2771. When encountering issues:
  2772. 1. **First Steps**
  2773. * Check server logs
  2774. * Test with [Inspector](/docs/tools/inspector)
  2775. * Review configuration
  2776. * Verify environment
  2777. 2. **Support Channels**
  2778. * GitHub issues
  2779. * GitHub discussions
  2780. 3. **Providing Information**
  2781. * Log excerpts
  2782. * Configuration files
  2783. * Steps to reproduce
  2784. * Environment details
  2785. ## Next steps
  2786. <CardGroup cols={2}>
  2787. <Card title="MCP Inspector" icon="magnifying-glass" href="/docs/tools/inspector">
  2788. Learn to use the MCP Inspector
  2789. </Card>
  2790. </CardGroup>
  2791. # Inspector
  2792. Source: https://modelcontextprotocol.io/docs/tools/inspector
  2793. In-depth guide to using the MCP Inspector for testing and debugging Model Context Protocol servers
  2794. The [MCP Inspector](https://github.com/modelcontextprotocol/inspector) is an interactive developer tool for testing and debugging MCP servers. While the [Debugging Guide](/docs/tools/debugging) covers the Inspector as part of the overall debugging toolkit, this document provides a detailed exploration of the Inspector's features and capabilities.
  2795. ## Getting started
  2796. ### Installation and basic usage
  2797. The Inspector runs directly through `npx` without requiring installation:
  2798. ```bash
  2799. npx @modelcontextprotocol/inspector <command>
  2800. ```
  2801. ```bash
  2802. npx @modelcontextprotocol/inspector <command> <arg1> <arg2>
  2803. ```
  2804. #### Inspecting servers from NPM or PyPi
  2805. A common way to start server packages from [NPM](https://npmjs.com) or [PyPi](https://pypi.com).
  2806. <Tabs>
  2807. <Tab title="NPM package">
  2808. ```bash
  2809. npx -y @modelcontextprotocol/inspector npx <package-name> <args>
  2810. # For example
  2811. npx -y @modelcontextprotocol/inspector npx server-postgres postgres://127.0.0.1/testdb
  2812. ```
  2813. </Tab>
  2814. <Tab title="PyPi package">
  2815. ```bash
  2816. npx @modelcontextprotocol/inspector uvx <package-name> <args>
  2817. # For example
  2818. npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git
  2819. ```
  2820. </Tab>
  2821. </Tabs>
  2822. #### Inspecting locally developed servers
  2823. To inspect servers locally developed or downloaded as a repository, the most common
  2824. way is:
  2825. <Tabs>
  2826. <Tab title="TypeScript">
  2827. ```bash
  2828. npx @modelcontextprotocol/inspector node path/to/server/index.js args...
  2829. ```
  2830. </Tab>
  2831. <Tab title="Python">
  2832. ```bash
  2833. npx @modelcontextprotocol/inspector \
  2834. uv \
  2835. --directory path/to/server \
  2836. run \
  2837. package-name \
  2838. args...
  2839. ```
  2840. </Tab>
  2841. </Tabs>
  2842. Please carefully read any attached README for the most accurate instructions.
  2843. ## Feature overview
  2844. <Frame caption="The MCP Inspector interface">
  2845. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/mcp-inspector.png" />
  2846. </Frame>
  2847. The Inspector provides several features for interacting with your MCP server:
  2848. ### Server connection pane
  2849. * Allows selecting the [transport](/docs/concepts/transports) for connecting to the server
  2850. * For local servers, supports customizing the command-line arguments and environment
  2851. ### Resources tab
  2852. * Lists all available resources
  2853. * Shows resource metadata (MIME types, descriptions)
  2854. * Allows resource content inspection
  2855. * Supports subscription testing
  2856. ### Prompts tab
  2857. * Displays available prompt templates
  2858. * Shows prompt arguments and descriptions
  2859. * Enables prompt testing with custom arguments
  2860. * Previews generated messages
  2861. ### Tools tab
  2862. * Lists available tools
  2863. * Shows tool schemas and descriptions
  2864. * Enables tool testing with custom inputs
  2865. * Displays tool execution results
  2866. ### Notifications pane
  2867. * Presents all logs recorded from the server
  2868. * Shows notifications received from the server
  2869. ## Best practices
  2870. ### Development workflow
  2871. 1. Start Development
  2872. * Launch Inspector with your server
  2873. * Verify basic connectivity
  2874. * Check capability negotiation
  2875. 2. Iterative testing
  2876. * Make server changes
  2877. * Rebuild the server
  2878. * Reconnect the Inspector
  2879. * Test affected features
  2880. * Monitor messages
  2881. 3. Test edge cases
  2882. * Invalid inputs
  2883. * Missing prompt arguments
  2884. * Concurrent operations
  2885. * Verify error handling and error responses
  2886. ## Next steps
  2887. <CardGroup cols={2}>
  2888. <Card title="Inspector Repository" icon="github" href="https://github.com/modelcontextprotocol/inspector">
  2889. Check out the MCP Inspector source code
  2890. </Card>
  2891. <Card title="Debugging Guide" icon="bug" href="/docs/tools/debugging">
  2892. Learn about broader debugging strategies
  2893. </Card>
  2894. </CardGroup>
  2895. # Example Servers
  2896. Source: https://modelcontextprotocol.io/examples
  2897. A list of example servers and implementations
  2898. This page showcases various Model Context Protocol (MCP) servers that demonstrate the protocol's capabilities and versatility. These servers enable Large Language Models (LLMs) to securely access tools and data sources.
  2899. ## Reference implementations
  2900. These official reference servers demonstrate core MCP features and SDK usage:
  2901. ### Current reference servers
  2902. * **[Filesystem](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem)** - Secure file operations with configurable access controls
  2903. * **[Fetch](https://github.com/modelcontextprotocol/servers/tree/main/src/fetch)** - Web content fetching and conversion optimized for LLM usage
  2904. * **[Memory](https://github.com/modelcontextprotocol/servers/tree/main/src/memory)** - Knowledge graph-based persistent memory system
  2905. * **[Sequential Thinking](https://github.com/modelcontextprotocol/servers/tree/main/src/sequentialthinking)** - Dynamic problem-solving through thought sequences
  2906. ### Archived servers (historical reference)
  2907. ⚠️ **Note**: The following servers have been moved to the [servers-archived repository](https://github.com/modelcontextprotocol/servers-archived) and are no longer actively maintained. They are provided for historical reference only.
  2908. #### Data and file systems
  2909. * **[PostgreSQL](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/postgres)** - Read-only database access with schema inspection capabilities
  2910. * **[SQLite](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/sqlite)** - Database interaction and business intelligence features
  2911. * **[Google Drive](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/gdrive)** - File access and search capabilities for Google Drive
  2912. #### Development tools
  2913. * **[Git](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/git)** - Tools to read, search, and manipulate Git repositories
  2914. * **[GitHub](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/github)** - Repository management, file operations, and GitHub API integration
  2915. * **[GitLab](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/gitlab)** - GitLab API integration enabling project management
  2916. * **[Sentry](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/sentry)** - Retrieving and analyzing issues from Sentry.io
  2917. #### Web and browser automation
  2918. * **[Brave Search](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/brave-search)** - Web and local search using Brave's Search API
  2919. * **[Puppeteer](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/puppeteer)** - Browser automation and web scraping capabilities
  2920. #### Productivity and communication
  2921. * **[Slack](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/slack)** - Channel management and messaging capabilities
  2922. * **[Google Maps](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/google-maps)** - Location services, directions, and place details
  2923. #### AI and specialized tools
  2924. * **[EverArt](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/everart)** - AI image generation using various models
  2925. * **[AWS KB Retrieval](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/aws-kb-retrieval-server)** - Retrieval from AWS Knowledge Base using Bedrock Agent Runtime
  2926. ## Official integrations
  2927. Visit the [MCP Servers Repository (Official Integrations section)](https://github.com/modelcontextprotocol/servers?tab=readme-ov-file#%EF%B8%8F-official-integrations) for a list of MCP servers maintained by companies for their platforms.
  2928. ## Community implementations
  2929. Visit the [MCP Servers Repository (Community section)](https://github.com/modelcontextprotocol/servers?tab=readme-ov-file#-community-servers) for a list of MCP servers maintained by community members.
  2930. ## Getting started
  2931. ### Using reference servers
  2932. TypeScript-based servers can be used directly with `npx`:
  2933. ```bash
  2934. npx -y @modelcontextprotocol/server-memory
  2935. ```
  2936. Python-based servers can be used with `uvx` (recommended) or `pip`:
  2937. ```bash
  2938. # Using uvx
  2939. uvx mcp-server-git
  2940. # Using pip
  2941. pip install mcp-server-git
  2942. python -m mcp_server_git
  2943. ```
  2944. ### Configuring with Claude
  2945. To use an MCP server with Claude, add it to your configuration:
  2946. ```json
  2947. {
  2948. "mcpServers": {
  2949. "memory": {
  2950. "command": "npx",
  2951. "args": ["-y", "@modelcontextprotocol/server-memory"]
  2952. },
  2953. "filesystem": {
  2954. "command": "npx",
  2955. "args": [
  2956. "-y",
  2957. "@modelcontextprotocol/server-filesystem",
  2958. "/path/to/allowed/files"
  2959. ]
  2960. },
  2961. "github": {
  2962. "command": "npx",
  2963. "args": ["-y", "@modelcontextprotocol/server-github"],
  2964. "env": {
  2965. "GITHUB_PERSONAL_ACCESS_TOKEN": "<YOUR_TOKEN>"
  2966. }
  2967. }
  2968. }
  2969. }
  2970. ```
  2971. ## Additional resources
  2972. Visit the [MCP Servers Repository (Resources section)](https://github.com/modelcontextprotocol/servers?tab=readme-ov-file#-resources) for a collection of other resources and projects related to MCP.
  2973. Visit our [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions) to engage with the MCP community.
  2974. # FAQs
  2975. Source: https://modelcontextprotocol.io/faqs
  2976. Explaining MCP and why it matters in simple terms
  2977. ## What is MCP?
  2978. MCP (Model Context Protocol) is a standard way for AI applications and agents to connect to and work with your data sources (e.g. local files, databases, or content repositories) and tools (e.g. GitHub, Google Maps, or Puppeteer).
  2979. Think of MCP as a universal adapter for AI applications, similar to what USB-C is for physical devices. USB-C acts as a universal adapter to connect devices to various peripherals and accessories. Similarly, MCP provides a standardized way to connect AI applications to different data and tools.
  2980. Before USB-C, you needed different cables for different connections. Similarly, before MCP, developers had to build custom connections to each data source or tool they wanted their AI application to work with—a time-consuming process that often resulted in limited functionality. Now, with MCP, developers can easily add connections to their AI applications, making their applications much more powerful from day one.
  2981. ## Why does MCP matter?
  2982. ### For AI application users
  2983. MCP means your AI applications can access the information and tools you work with every day, making them much more helpful. Rather than AI being limited to what it already knows about, it can now understand your specific documents, data, and work context.
  2984. For example, by using MCP servers, applications can access your personal documents from Google Drive or data about your codebase from GitHub, providing more personalized and contextually relevant assistance.
  2985. Imagine asking an AI assistant: "Summarize last week's team meeting notes and schedule follow-ups with everyone."
  2986. By using connections to data sources powered by MCP, the AI assistant can:
  2987. * Connect to your Google Drive through an MCP server to read meeting notes
  2988. * Understand who needs follow-ups based on the notes
  2989. * Connect to your calendar through another MCP server to schedule the meetings automatically
  2990. ### For developers
  2991. MCP reduces development time and complexity when building AI applications that need to access various data sources. With MCP, developers can focus on building great AI experiences rather than repeatedly creating custom connectors.
  2992. Traditionally, connecting applications with data sources required building custom, one-off connections for each data source and each application. This created significant duplicative work—every developer wanting to connect their AI application to Google Drive or Slack needed to build their own connection.
  2993. MCP simplifies this by enabling developers to build MCP servers for data sources that are then reusable by various applications. For example, using the open source Google Drive MCP server, many different applications can access data from Google Drive without each developer needing to build a custom connection.
  2994. This open source ecosystem of MCP servers means developers can leverage existing work rather than starting from scratch, making it easier to build powerful AI applications that seamlessly integrate with the tools and data sources their users already rely on.
  2995. ## How does MCP work?
  2996. <Frame>
  2997. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/mcp-simple-diagram.png" />
  2998. </Frame>
  2999. MCP creates a bridge between your AI applications and your data through a straightforward system:
  3000. * **MCP servers** connect to your data sources and tools (like Google Drive or Slack)
  3001. * **MCP clients** are run by AI applications (like Claude Desktop) to connect them to these servers
  3002. * When you give permission, your AI application discovers available MCP servers
  3003. * The AI model can then use these connections to read information and take actions
  3004. This modular system means new capabilities can be added without changing AI applications themselves—just like adding new accessories to your computer without upgrading your entire system.
  3005. ## Who creates and maintains MCP servers?
  3006. MCP servers are developed and maintained by:
  3007. * Developers at Anthropic who build servers for common tools and data sources
  3008. * Open source contributors who create servers for tools they use
  3009. * Enterprise development teams building servers for their internal systems
  3010. * Software providers making their applications AI-ready
  3011. Once an open source MCP server is created for a data source, it can be used by any MCP-compatible AI application, creating a growing ecosystem of connections. See our [list of example servers](https://modelcontextprotocol.io/examples), or [get started building your own server](https://modelcontextprotocol.io/quickstart/server).
  3012. # Introduction
  3013. Source: https://modelcontextprotocol.io/introduction
  3014. Get started with the Model Context Protocol (MCP)
  3015. MCP is an open protocol that standardizes how applications provide context to LLMs. Think of MCP like a USB-C port for AI applications. Just as USB-C provides a standardized way to connect your devices to various peripherals and accessories, MCP provides a standardized way to connect AI models to different data sources and tools.
  3016. ## Why MCP?
  3017. MCP helps you build agents and complex workflows on top of LLMs. LLMs frequently need to integrate with data and tools, and MCP provides:
  3018. * A growing list of pre-built integrations that your LLM can directly plug into
  3019. * The flexibility to switch between LLM providers and vendors
  3020. * Best practices for securing your data within your infrastructure
  3021. ### General architecture
  3022. At its core, MCP follows a client-server architecture where a host application can connect to multiple servers:
  3023. ```mermaid
  3024. flowchart LR
  3025. subgraph "Your Computer"
  3026. Host["Host with MCP Client\n(Claude, IDEs, Tools)"]
  3027. S1["MCP Server A"]
  3028. S2["MCP Server B"]
  3029. S3["MCP Server C"]
  3030. Host <-->|"MCP Protocol"| S1
  3031. Host <-->|"MCP Protocol"| S2
  3032. Host <-->|"MCP Protocol"| S3
  3033. S1 <--> D1[("Local\nData Source A")]
  3034. S2 <--> D2[("Local\nData Source B")]
  3035. end
  3036. subgraph "Internet"
  3037. S3 <-->|"Web APIs"| D3[("Remote\nService C")]
  3038. end
  3039. ```
  3040. * **MCP Hosts**: Programs like Claude Desktop, IDEs, or AI tools that want to access data through MCP
  3041. * **MCP Clients**: Protocol clients that maintain 1:1 connections with servers
  3042. * **MCP Servers**: Lightweight programs that each expose specific capabilities through the standardized Model Context Protocol
  3043. * **Local Data Sources**: Your computer's files, databases, and services that MCP servers can securely access
  3044. * **Remote Services**: External systems available over the internet (e.g., through APIs) that MCP servers can connect to
  3045. ## Get started
  3046. Choose the path that best fits your needs:
  3047. ### Quick Starts
  3048. <CardGroup cols={2}>
  3049. <Card title="For Server Developers" icon="bolt" href="/quickstart/server">
  3050. Get started building your own server to use in Claude for Desktop and other
  3051. clients
  3052. </Card>
  3053. <Card title="For Client Developers" icon="bolt" href="/quickstart/client">
  3054. Get started building your own client that can integrate with all MCP servers
  3055. </Card>
  3056. <Card title="For Claude Desktop Users" icon="bolt" href="/quickstart/user">
  3057. Get started using pre-built servers in Claude for Desktop
  3058. </Card>
  3059. </CardGroup>
  3060. ### Examples
  3061. <CardGroup cols={2}>
  3062. <Card title="Example Servers" icon="grid" href="/examples">
  3063. Check out our gallery of official MCP servers and implementations
  3064. </Card>
  3065. <Card title="Example Clients" icon="cubes" href="/clients">
  3066. View the list of clients that support MCP integrations
  3067. </Card>
  3068. </CardGroup>
  3069. ## Tutorials
  3070. <CardGroup cols={2}>
  3071. <Card title="Building MCP with LLMs" icon="comments" href="/tutorials/building-mcp-with-llms">
  3072. Learn how to use LLMs like Claude to speed up your MCP development
  3073. </Card>
  3074. <Card title="Debugging Guide" icon="bug" href="/docs/tools/debugging">
  3075. Learn how to effectively debug MCP servers and integrations
  3076. </Card>
  3077. <Card title="MCP Inspector" icon="magnifying-glass" href="/docs/tools/inspector">
  3078. Test and inspect your MCP servers with our interactive debugging tool
  3079. </Card>
  3080. <Card title="MCP Workshop (Video, 2hr)" icon="person-chalkboard" href="https://www.youtube.com/watch?v=kQmXtrmQ5Zg">
  3081. <iframe src="https://www.youtube.com/embed/kQmXtrmQ5Zg" />
  3082. </Card>
  3083. </CardGroup>
  3084. ## Explore MCP
  3085. Dive deeper into MCP's core concepts and capabilities:
  3086. <CardGroup cols={2}>
  3087. <Card title="Core architecture" icon="sitemap" href="/docs/concepts/architecture">
  3088. Understand how MCP connects clients, servers, and LLMs
  3089. </Card>
  3090. <Card title="Resources" icon="database" href="/docs/concepts/resources">
  3091. Expose data and content from your servers to LLMs
  3092. </Card>
  3093. <Card title="Prompts" icon="message" href="/docs/concepts/prompts">
  3094. Create reusable prompt templates and workflows
  3095. </Card>
  3096. <Card title="Tools" icon="wrench" href="/docs/concepts/tools">
  3097. Enable LLMs to perform actions through your server
  3098. </Card>
  3099. <Card title="Sampling" icon="robot" href="/docs/concepts/sampling">
  3100. Let your servers request completions from LLMs
  3101. </Card>
  3102. <Card title="Transports" icon="network-wired" href="/docs/concepts/transports">
  3103. Learn about MCP's communication mechanism
  3104. </Card>
  3105. </CardGroup>
  3106. ## Contributing
  3107. Want to contribute? Check out our [Contributing Guide](/development/contributing) to learn how you can help improve MCP.
  3108. ## Support and Feedback
  3109. Here's how to get help or provide feedback:
  3110. * For bug reports and feature requests related to the MCP specification, SDKs, or documentation (open source), please [create a GitHub issue](https://github.com/modelcontextprotocol)
  3111. * For discussions or Q\&A about the MCP specification, use the [specification discussions](https://github.com/modelcontextprotocol/specification/discussions)
  3112. * For discussions or Q\&A about other MCP open source components, use the [organization discussions](https://github.com/orgs/modelcontextprotocol/discussions)
  3113. * For bug reports, feature requests, and questions related to Claude.app and claude.ai's MCP integration, please see Anthropic's guide on [How to Get Support](https://support.anthropic.com/en/articles/9015913-how-to-get-support)
  3114. # For Client Developers
  3115. Source: https://modelcontextprotocol.io/quickstart/client
  3116. Get started building your own client that can integrate with all MCP servers.
  3117. In this tutorial, you'll learn how to build a LLM-powered chatbot client that connects to MCP servers. It helps to have gone through the [Server quickstart](/quickstart/server) that guides you through the basic of building your first server.
  3118. <Tabs>
  3119. <Tab title="Python">
  3120. [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-python)
  3121. ## System Requirements
  3122. Before starting, ensure your system meets these requirements:
  3123. * Mac or Windows computer
  3124. * Latest Python version installed
  3125. * Latest version of `uv` installed
  3126. ## Setting Up Your Environment
  3127. First, create a new Python project with `uv`:
  3128. ```bash
  3129. # Create project directory
  3130. uv init mcp-client
  3131. cd mcp-client
  3132. # Create virtual environment
  3133. uv venv
  3134. # Activate virtual environment
  3135. # On Windows:
  3136. .venv\Scripts\activate
  3137. # On Unix or MacOS:
  3138. source .venv/bin/activate
  3139. # Install required packages
  3140. uv add mcp anthropic python-dotenv
  3141. # Remove boilerplate files
  3142. # On Windows:
  3143. del main.py
  3144. # On Unix or MacOS:
  3145. rm main.py
  3146. # Create our main file
  3147. touch client.py
  3148. ```
  3149. ## Setting Up Your API Key
  3150. You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
  3151. Create a `.env` file to store it:
  3152. ```bash
  3153. # Create .env file
  3154. touch .env
  3155. ```
  3156. Add your key to the `.env` file:
  3157. ```bash
  3158. ANTHROPIC_API_KEY=<your key here>
  3159. ```
  3160. Add `.env` to your `.gitignore`:
  3161. ```bash
  3162. echo ".env" >> .gitignore
  3163. ```
  3164. <Warning>
  3165. Make sure you keep your `ANTHROPIC_API_KEY` secure!
  3166. </Warning>
  3167. ## Creating the Client
  3168. ### Basic Client Structure
  3169. First, let's set up our imports and create the basic client class:
  3170. ```python
  3171. import asyncio
  3172. from typing import Optional
  3173. from contextlib import AsyncExitStack
  3174. from mcp import ClientSession, StdioServerParameters
  3175. from mcp.client.stdio import stdio_client
  3176. from anthropic import Anthropic
  3177. from dotenv import load_dotenv
  3178. load_dotenv() # load environment variables from .env
  3179. class MCPClient:
  3180. def __init__(self):
  3181. # Initialize session and client objects
  3182. self.session: Optional[ClientSession] = None
  3183. self.exit_stack = AsyncExitStack()
  3184. self.anthropic = Anthropic()
  3185. # methods will go here
  3186. ```
  3187. ### Server Connection Management
  3188. Next, we'll implement the method to connect to an MCP server:
  3189. ```python
  3190. async def connect_to_server(self, server_script_path: str):
  3191. """Connect to an MCP server
  3192. Args:
  3193. server_script_path: Path to the server script (.py or .js)
  3194. """
  3195. is_python = server_script_path.endswith('.py')
  3196. is_js = server_script_path.endswith('.js')
  3197. if not (is_python or is_js):
  3198. raise ValueError("Server script must be a .py or .js file")
  3199. command = "python" if is_python else "node"
  3200. server_params = StdioServerParameters(
  3201. command=command,
  3202. args=[server_script_path],
  3203. env=None
  3204. )
  3205. stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
  3206. self.stdio, self.write = stdio_transport
  3207. self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))
  3208. await self.session.initialize()
  3209. # List available tools
  3210. response = await self.session.list_tools()
  3211. tools = response.tools
  3212. print("\nConnected to server with tools:", [tool.name for tool in tools])
  3213. ```
  3214. ### Query Processing Logic
  3215. Now let's add the core functionality for processing queries and handling tool calls:
  3216. ```python
  3217. async def process_query(self, query: str) -> str:
  3218. """Process a query using Claude and available tools"""
  3219. messages = [
  3220. {
  3221. "role": "user",
  3222. "content": query
  3223. }
  3224. ]
  3225. response = await self.session.list_tools()
  3226. available_tools = [{
  3227. "name": tool.name,
  3228. "description": tool.description,
  3229. "input_schema": tool.inputSchema
  3230. } for tool in response.tools]
  3231. # Initial Claude API call
  3232. response = self.anthropic.messages.create(
  3233. model="claude-3-5-sonnet-20241022",
  3234. max_tokens=1000,
  3235. messages=messages,
  3236. tools=available_tools
  3237. )
  3238. # Process response and handle tool calls
  3239. final_text = []
  3240. assistant_message_content = []
  3241. for content in response.content:
  3242. if content.type == 'text':
  3243. final_text.append(content.text)
  3244. assistant_message_content.append(content)
  3245. elif content.type == 'tool_use':
  3246. tool_name = content.name
  3247. tool_args = content.input
  3248. # Execute tool call
  3249. result = await self.session.call_tool(tool_name, tool_args)
  3250. final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")
  3251. assistant_message_content.append(content)
  3252. messages.append({
  3253. "role": "assistant",
  3254. "content": assistant_message_content
  3255. })
  3256. messages.append({
  3257. "role": "user",
  3258. "content": [
  3259. {
  3260. "type": "tool_result",
  3261. "tool_use_id": content.id,
  3262. "content": result.content
  3263. }
  3264. ]
  3265. })
  3266. # Get next response from Claude
  3267. response = self.anthropic.messages.create(
  3268. model="claude-3-5-sonnet-20241022",
  3269. max_tokens=1000,
  3270. messages=messages,
  3271. tools=available_tools
  3272. )
  3273. final_text.append(response.content[0].text)
  3274. return "\n".join(final_text)
  3275. ```
  3276. ### Interactive Chat Interface
  3277. Now we'll add the chat loop and cleanup functionality:
  3278. ```python
  3279. async def chat_loop(self):
  3280. """Run an interactive chat loop"""
  3281. print("\nMCP Client Started!")
  3282. print("Type your queries or 'quit' to exit.")
  3283. while True:
  3284. try:
  3285. query = input("\nQuery: ").strip()
  3286. if query.lower() == 'quit':
  3287. break
  3288. response = await self.process_query(query)
  3289. print("\n" + response)
  3290. except Exception as e:
  3291. print(f"\nError: {str(e)}")
  3292. async def cleanup(self):
  3293. """Clean up resources"""
  3294. await self.exit_stack.aclose()
  3295. ```
  3296. ### Main Entry Point
  3297. Finally, we'll add the main execution logic:
  3298. ```python
  3299. async def main():
  3300. if len(sys.argv) < 2:
  3301. print("Usage: python client.py <path_to_server_script>")
  3302. sys.exit(1)
  3303. client = MCPClient()
  3304. try:
  3305. await client.connect_to_server(sys.argv[1])
  3306. await client.chat_loop()
  3307. finally:
  3308. await client.cleanup()
  3309. if __name__ == "__main__":
  3310. import sys
  3311. asyncio.run(main())
  3312. ```
  3313. You can find the complete `client.py` file [here.](https://gist.github.com/zckly/f3f28ea731e096e53b39b47bf0a2d4b1)
  3314. ## Key Components Explained
  3315. ### 1. Client Initialization
  3316. * The `MCPClient` class initializes with session management and API clients
  3317. * Uses `AsyncExitStack` for proper resource management
  3318. * Configures the Anthropic client for Claude interactions
  3319. ### 2. Server Connection
  3320. * Supports both Python and Node.js servers
  3321. * Validates server script type
  3322. * Sets up proper communication channels
  3323. * Initializes the session and lists available tools
  3324. ### 3. Query Processing
  3325. * Maintains conversation context
  3326. * Handles Claude's responses and tool calls
  3327. * Manages the message flow between Claude and tools
  3328. * Combines results into a coherent response
  3329. ### 4. Interactive Interface
  3330. * Provides a simple command-line interface
  3331. * Handles user input and displays responses
  3332. * Includes basic error handling
  3333. * Allows graceful exit
  3334. ### 5. Resource Management
  3335. * Proper cleanup of resources
  3336. * Error handling for connection issues
  3337. * Graceful shutdown procedures
  3338. ## Common Customization Points
  3339. 1. **Tool Handling**
  3340. * Modify `process_query()` to handle specific tool types
  3341. * Add custom error handling for tool calls
  3342. * Implement tool-specific response formatting
  3343. 2. **Response Processing**
  3344. * Customize how tool results are formatted
  3345. * Add response filtering or transformation
  3346. * Implement custom logging
  3347. 3. **User Interface**
  3348. * Add a GUI or web interface
  3349. * Implement rich console output
  3350. * Add command history or auto-completion
  3351. ## Running the Client
  3352. To run your client with any MCP server:
  3353. ```bash
  3354. uv run client.py path/to/server.py # python server
  3355. uv run client.py path/to/build/index.js # node server
  3356. ```
  3357. <Note>
  3358. If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `python client.py .../quickstart-resources/weather-server-python/weather.py`
  3359. </Note>
  3360. The client will:
  3361. 1. Connect to the specified server
  3362. 2. List available tools
  3363. 3. Start an interactive chat session where you can:
  3364. * Enter queries
  3365. * See tool executions
  3366. * Get responses from Claude
  3367. Here's an example of what it should look like if connected to the weather server from the server quickstart:
  3368. <Frame>
  3369. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/client-claude-cli-python.png" />
  3370. </Frame>
  3371. ## How It Works
  3372. When you submit a query:
  3373. 1. The client gets the list of available tools from the server
  3374. 2. Your query is sent to Claude along with tool descriptions
  3375. 3. Claude decides which tools (if any) to use
  3376. 4. The client executes any requested tool calls through the server
  3377. 5. Results are sent back to Claude
  3378. 6. Claude provides a natural language response
  3379. 7. The response is displayed to you
  3380. ## Best practices
  3381. 1. **Error Handling**
  3382. * Always wrap tool calls in try-catch blocks
  3383. * Provide meaningful error messages
  3384. * Gracefully handle connection issues
  3385. 2. **Resource Management**
  3386. * Use `AsyncExitStack` for proper cleanup
  3387. * Close connections when done
  3388. * Handle server disconnections
  3389. 3. **Security**
  3390. * Store API keys securely in `.env`
  3391. * Validate server responses
  3392. * Be cautious with tool permissions
  3393. ## Troubleshooting
  3394. ### Server Path Issues
  3395. * Double-check the path to your server script is correct
  3396. * Use the absolute path if the relative path isn't working
  3397. * For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
  3398. * Verify the server file has the correct extension (.py for Python or .js for Node.js)
  3399. Example of correct path usage:
  3400. ```bash
  3401. # Relative path
  3402. uv run client.py ./server/weather.py
  3403. # Absolute path
  3404. uv run client.py /Users/username/projects/mcp-server/weather.py
  3405. # Windows path (either format works)
  3406. uv run client.py C:/projects/mcp-server/weather.py
  3407. uv run client.py C:\\projects\\mcp-server\\weather.py
  3408. ```
  3409. ### Response Timing
  3410. * The first response might take up to 30 seconds to return
  3411. * This is normal and happens while:
  3412. * The server initializes
  3413. * Claude processes the query
  3414. * Tools are being executed
  3415. * Subsequent responses are typically faster
  3416. * Don't interrupt the process during this initial waiting period
  3417. ### Common Error Messages
  3418. If you see:
  3419. * `FileNotFoundError`: Check your server path
  3420. * `Connection refused`: Ensure the server is running and the path is correct
  3421. * `Tool execution failed`: Verify the tool's required environment variables are set
  3422. * `Timeout error`: Consider increasing the timeout in your client configuration
  3423. </Tab>
  3424. <Tab title="Node">
  3425. [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-typescript)
  3426. ## System Requirements
  3427. Before starting, ensure your system meets these requirements:
  3428. * Mac or Windows computer
  3429. * Node.js 17 or higher installed
  3430. * Latest version of `npm` installed
  3431. * Anthropic API key (Claude)
  3432. ## Setting Up Your Environment
  3433. First, let's create and set up our project:
  3434. <CodeGroup>
  3435. ```bash MacOS/Linux
  3436. # Create project directory
  3437. mkdir mcp-client-typescript
  3438. cd mcp-client-typescript
  3439. # Initialize npm project
  3440. npm init -y
  3441. # Install dependencies
  3442. npm install @anthropic-ai/sdk @modelcontextprotocol/sdk dotenv
  3443. # Install dev dependencies
  3444. npm install -D @types/node typescript
  3445. # Create source file
  3446. touch index.ts
  3447. ```
  3448. ```powershell Windows
  3449. # Create project directory
  3450. md mcp-client-typescript
  3451. cd mcp-client-typescript
  3452. # Initialize npm project
  3453. npm init -y
  3454. # Install dependencies
  3455. npm install @anthropic-ai/sdk @modelcontextprotocol/sdk dotenv
  3456. # Install dev dependencies
  3457. npm install -D @types/node typescript
  3458. # Create source file
  3459. new-item index.ts
  3460. ```
  3461. </CodeGroup>
  3462. Update your `package.json` to set `type: "module"` and a build script:
  3463. ```json package.json
  3464. {
  3465. "type": "module",
  3466. "scripts": {
  3467. "build": "tsc && chmod 755 build/index.js"
  3468. }
  3469. }
  3470. ```
  3471. Create a `tsconfig.json` in the root of your project:
  3472. ```json tsconfig.json
  3473. {
  3474. "compilerOptions": {
  3475. "target": "ES2022",
  3476. "module": "Node16",
  3477. "moduleResolution": "Node16",
  3478. "outDir": "./build",
  3479. "rootDir": "./",
  3480. "strict": true,
  3481. "esModuleInterop": true,
  3482. "skipLibCheck": true,
  3483. "forceConsistentCasingInFileNames": true
  3484. },
  3485. "include": ["index.ts"],
  3486. "exclude": ["node_modules"]
  3487. }
  3488. ```
  3489. ## Setting Up Your API Key
  3490. You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
  3491. Create a `.env` file to store it:
  3492. ```bash
  3493. echo "ANTHROPIC_API_KEY=<your key here>" > .env
  3494. ```
  3495. Add `.env` to your `.gitignore`:
  3496. ```bash
  3497. echo ".env" >> .gitignore
  3498. ```
  3499. <Warning>
  3500. Make sure you keep your `ANTHROPIC_API_KEY` secure!
  3501. </Warning>
  3502. ## Creating the Client
  3503. ### Basic Client Structure
  3504. First, let's set up our imports and create the basic client class in `index.ts`:
  3505. ```typescript
  3506. import { Anthropic } from "@anthropic-ai/sdk";
  3507. import {
  3508. MessageParam,
  3509. Tool,
  3510. } from "@anthropic-ai/sdk/resources/messages/messages.mjs";
  3511. import { Client } from "@modelcontextprotocol/sdk/client/index.js";
  3512. import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
  3513. import readline from "readline/promises";
  3514. import dotenv from "dotenv";
  3515. dotenv.config();
  3516. const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
  3517. if (!ANTHROPIC_API_KEY) {
  3518. throw new Error("ANTHROPIC_API_KEY is not set");
  3519. }
  3520. class MCPClient {
  3521. private mcp: Client;
  3522. private anthropic: Anthropic;
  3523. private transport: StdioClientTransport | null = null;
  3524. private tools: Tool[] = [];
  3525. constructor() {
  3526. this.anthropic = new Anthropic({
  3527. apiKey: ANTHROPIC_API_KEY,
  3528. });
  3529. this.mcp = new Client({ name: "mcp-client-cli", version: "1.0.0" });
  3530. }
  3531. // methods will go here
  3532. }
  3533. ```
  3534. ### Server Connection Management
  3535. Next, we'll implement the method to connect to an MCP server:
  3536. ```typescript
  3537. async connectToServer(serverScriptPath: string) {
  3538. try {
  3539. const isJs = serverScriptPath.endsWith(".js");
  3540. const isPy = serverScriptPath.endsWith(".py");
  3541. if (!isJs && !isPy) {
  3542. throw new Error("Server script must be a .js or .py file");
  3543. }
  3544. const command = isPy
  3545. ? process.platform === "win32"
  3546. ? "python"
  3547. : "python3"
  3548. : process.execPath;
  3549. this.transport = new StdioClientTransport({
  3550. command,
  3551. args: [serverScriptPath],
  3552. });
  3553. this.mcp.connect(this.transport);
  3554. const toolsResult = await this.mcp.listTools();
  3555. this.tools = toolsResult.tools.map((tool) => {
  3556. return {
  3557. name: tool.name,
  3558. description: tool.description,
  3559. input_schema: tool.inputSchema,
  3560. };
  3561. });
  3562. console.log(
  3563. "Connected to server with tools:",
  3564. this.tools.map(({ name }) => name)
  3565. );
  3566. } catch (e) {
  3567. console.log("Failed to connect to MCP server: ", e);
  3568. throw e;
  3569. }
  3570. }
  3571. ```
  3572. ### Query Processing Logic
  3573. Now let's add the core functionality for processing queries and handling tool calls:
  3574. ```typescript
  3575. async processQuery(query: string) {
  3576. const messages: MessageParam[] = [
  3577. {
  3578. role: "user",
  3579. content: query,
  3580. },
  3581. ];
  3582. const response = await this.anthropic.messages.create({
  3583. model: "claude-3-5-sonnet-20241022",
  3584. max_tokens: 1000,
  3585. messages,
  3586. tools: this.tools,
  3587. });
  3588. const finalText = [];
  3589. const toolResults = [];
  3590. for (const content of response.content) {
  3591. if (content.type === "text") {
  3592. finalText.push(content.text);
  3593. } else if (content.type === "tool_use") {
  3594. const toolName = content.name;
  3595. const toolArgs = content.input as { [x: string]: unknown } | undefined;
  3596. const result = await this.mcp.callTool({
  3597. name: toolName,
  3598. arguments: toolArgs,
  3599. });
  3600. toolResults.push(result);
  3601. finalText.push(
  3602. `[Calling tool ${toolName} with args ${JSON.stringify(toolArgs)}]`
  3603. );
  3604. messages.push({
  3605. role: "user",
  3606. content: result.content as string,
  3607. });
  3608. const response = await this.anthropic.messages.create({
  3609. model: "claude-3-5-sonnet-20241022",
  3610. max_tokens: 1000,
  3611. messages,
  3612. });
  3613. finalText.push(
  3614. response.content[0].type === "text" ? response.content[0].text : ""
  3615. );
  3616. }
  3617. }
  3618. return finalText.join("\n");
  3619. }
  3620. ```
  3621. ### Interactive Chat Interface
  3622. Now we'll add the chat loop and cleanup functionality:
  3623. ```typescript
  3624. async chatLoop() {
  3625. const rl = readline.createInterface({
  3626. input: process.stdin,
  3627. output: process.stdout,
  3628. });
  3629. try {
  3630. console.log("\nMCP Client Started!");
  3631. console.log("Type your queries or 'quit' to exit.");
  3632. while (true) {
  3633. const message = await rl.question("\nQuery: ");
  3634. if (message.toLowerCase() === "quit") {
  3635. break;
  3636. }
  3637. const response = await this.processQuery(message);
  3638. console.log("\n" + response);
  3639. }
  3640. } finally {
  3641. rl.close();
  3642. }
  3643. }
  3644. async cleanup() {
  3645. await this.mcp.close();
  3646. }
  3647. ```
  3648. ### Main Entry Point
  3649. Finally, we'll add the main execution logic:
  3650. ```typescript
  3651. async function main() {
  3652. if (process.argv.length < 3) {
  3653. console.log("Usage: node index.ts <path_to_server_script>");
  3654. return;
  3655. }
  3656. const mcpClient = new MCPClient();
  3657. try {
  3658. await mcpClient.connectToServer(process.argv[2]);
  3659. await mcpClient.chatLoop();
  3660. } finally {
  3661. await mcpClient.cleanup();
  3662. process.exit(0);
  3663. }
  3664. }
  3665. main();
  3666. ```
  3667. ## Running the Client
  3668. To run your client with any MCP server:
  3669. ```bash
  3670. # Build TypeScript
  3671. npm run build
  3672. # Run the client
  3673. node build/index.js path/to/server.py # python server
  3674. node build/index.js path/to/build/index.js # node server
  3675. ```
  3676. <Note>
  3677. If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `node build/index.js .../quickstart-resources/weather-server-typescript/build/index.js`
  3678. </Note>
  3679. **The client will:**
  3680. 1. Connect to the specified server
  3681. 2. List available tools
  3682. 3. Start an interactive chat session where you can:
  3683. * Enter queries
  3684. * See tool executions
  3685. * Get responses from Claude
  3686. ## How It Works
  3687. When you submit a query:
  3688. 1. The client gets the list of available tools from the server
  3689. 2. Your query is sent to Claude along with tool descriptions
  3690. 3. Claude decides which tools (if any) to use
  3691. 4. The client executes any requested tool calls through the server
  3692. 5. Results are sent back to Claude
  3693. 6. Claude provides a natural language response
  3694. 7. The response is displayed to you
  3695. ## Best practices
  3696. 1. **Error Handling**
  3697. * Use TypeScript's type system for better error detection
  3698. * Wrap tool calls in try-catch blocks
  3699. * Provide meaningful error messages
  3700. * Gracefully handle connection issues
  3701. 2. **Security**
  3702. * Store API keys securely in `.env`
  3703. * Validate server responses
  3704. * Be cautious with tool permissions
  3705. ## Troubleshooting
  3706. ### Server Path Issues
  3707. * Double-check the path to your server script is correct
  3708. * Use the absolute path if the relative path isn't working
  3709. * For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
  3710. * Verify the server file has the correct extension (.js for Node.js or .py for Python)
  3711. Example of correct path usage:
  3712. ```bash
  3713. # Relative path
  3714. node build/index.js ./server/build/index.js
  3715. # Absolute path
  3716. node build/index.js /Users/username/projects/mcp-server/build/index.js
  3717. # Windows path (either format works)
  3718. node build/index.js C:/projects/mcp-server/build/index.js
  3719. node build/index.js C:\\projects\\mcp-server\\build\\index.js
  3720. ```
  3721. ### Response Timing
  3722. * The first response might take up to 30 seconds to return
  3723. * This is normal and happens while:
  3724. * The server initializes
  3725. * Claude processes the query
  3726. * Tools are being executed
  3727. * Subsequent responses are typically faster
  3728. * Don't interrupt the process during this initial waiting period
  3729. ### Common Error Messages
  3730. If you see:
  3731. * `Error: Cannot find module`: Check your build folder and ensure TypeScript compilation succeeded
  3732. * `Connection refused`: Ensure the server is running and the path is correct
  3733. * `Tool execution failed`: Verify the tool's required environment variables are set
  3734. * `ANTHROPIC_API_KEY is not set`: Check your .env file and environment variables
  3735. * `TypeError`: Ensure you're using the correct types for tool arguments
  3736. </Tab>
  3737. <Tab title="Java">
  3738. <Note>
  3739. This is a quickstart demo based on Spring AI MCP auto-configuration and boot starters.
  3740. To learn how to create sync and async MCP Clients manually, consult the [Java SDK Client](/sdk/java/mcp-client) documentation
  3741. </Note>
  3742. This example demonstrates how to build an interactive chatbot that combines Spring AI's Model Context Protocol (MCP) with the [Brave Search MCP Server](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/brave-search). The application creates a conversational interface powered by Anthropic's Claude AI model that can perform internet searches through Brave Search, enabling natural language interactions with real-time web data.
  3743. [You can find the complete code for this tutorial here.](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/web-search/brave-chatbot)
  3744. ## System Requirements
  3745. Before starting, ensure your system meets these requirements:
  3746. * Java 17 or higher
  3747. * Maven 3.6+
  3748. * npx package manager
  3749. * Anthropic API key (Claude)
  3750. * Brave Search API key
  3751. ## Setting Up Your Environment
  3752. 1. Install npx (Node Package eXecute):
  3753. First, make sure to install [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)
  3754. and then run:
  3755. ```bash
  3756. npm install -g npx
  3757. ```
  3758. 2. Clone the repository:
  3759. ```bash
  3760. git clone https://github.com/spring-projects/spring-ai-examples.git
  3761. cd model-context-protocol/brave-chatbot
  3762. ```
  3763. 3. Set up your API keys:
  3764. ```bash
  3765. export ANTHROPIC_API_KEY='your-anthropic-api-key-here'
  3766. export BRAVE_API_KEY='your-brave-api-key-here'
  3767. ```
  3768. 4. Build the application:
  3769. ```bash
  3770. ./mvnw clean install
  3771. ```
  3772. 5. Run the application using Maven:
  3773. ```bash
  3774. ./mvnw spring-boot:run
  3775. ```
  3776. <Warning>
  3777. Make sure you keep your `ANTHROPIC_API_KEY` and `BRAVE_API_KEY` keys secure!
  3778. </Warning>
  3779. ## How it Works
  3780. The application integrates Spring AI with the Brave Search MCP server through several components:
  3781. ### MCP Client Configuration
  3782. 1. Required dependencies in pom.xml:
  3783. ```xml
  3784. <dependency>
  3785. <groupId>org.springframework.ai</groupId>
  3786. <artifactId>spring-ai-starter-mcp-client</artifactId>
  3787. </dependency>
  3788. <dependency>
  3789. <groupId>org.springframework.ai</groupId>
  3790. <artifactId>spring-ai-starter-model-anthropic</artifactId>
  3791. </dependency>
  3792. ```
  3793. 2. Application properties (application.yml):
  3794. ```yml
  3795. spring:
  3796. ai:
  3797. mcp:
  3798. client:
  3799. enabled: true
  3800. name: brave-search-client
  3801. version: 1.0.0
  3802. type: SYNC
  3803. request-timeout: 20s
  3804. stdio:
  3805. root-change-notification: true
  3806. servers-configuration: classpath:/mcp-servers-config.json
  3807. toolcallback:
  3808. enabled: true
  3809. anthropic:
  3810. api-key: ${ANTHROPIC_API_KEY}
  3811. ```
  3812. This activates the `spring-ai-starter-mcp-client` to create one or more `McpClient`s based on the provided server configuration.
  3813. The `spring.ai.mcp.client.toolcallback.enabled=true` property enables the tool callback mechanism, that automatically registers all MCP tool as spring ai tools.
  3814. It is disabled by default.
  3815. 3. MCP Server Configuration (`mcp-servers-config.json`):
  3816. ```json
  3817. {
  3818. "mcpServers": {
  3819. "brave-search": {
  3820. "command": "npx",
  3821. "args": ["-y", "@modelcontextprotocol/server-brave-search"],
  3822. "env": {
  3823. "BRAVE_API_KEY": "<PUT YOUR BRAVE API KEY>"
  3824. }
  3825. }
  3826. }
  3827. }
  3828. ```
  3829. ### Chat Implementation
  3830. The chatbot is implemented using Spring AI's ChatClient with MCP tool integration:
  3831. ```java
  3832. var chatClient = chatClientBuilder
  3833. .defaultSystem("You are useful assistant, expert in AI and Java.")
  3834. .defaultToolCallbacks((Object[]) mcpToolAdapter.toolCallbacks())
  3835. .defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory()))
  3836. .build();
  3837. ```
  3838. <Warning>
  3839. Breaking change: From SpringAI 1.0.0-M8 onwards, use `.defaultToolCallbacks(...)` instead of `.defaultTool(...)` to register MCP tools.
  3840. </Warning>
  3841. Key features:
  3842. * Uses Claude AI model for natural language understanding
  3843. * Integrates Brave Search through MCP for real-time web search capabilities
  3844. * Maintains conversation memory using InMemoryChatMemory
  3845. * Runs as an interactive command-line application
  3846. ### Build and run
  3847. ```bash
  3848. ./mvnw clean install
  3849. java -jar ./target/ai-mcp-brave-chatbot-0.0.1-SNAPSHOT.jar
  3850. ```
  3851. or
  3852. ```bash
  3853. ./mvnw spring-boot:run
  3854. ```
  3855. The application will start an interactive chat session where you can ask questions. The chatbot will use Brave Search when it needs to find information from the internet to answer your queries.
  3856. The chatbot can:
  3857. * Answer questions using its built-in knowledge
  3858. * Perform web searches when needed using Brave Search
  3859. * Remember context from previous messages in the conversation
  3860. * Combine information from multiple sources to provide comprehensive answers
  3861. ### Advanced Configuration
  3862. The MCP client supports additional configuration options:
  3863. * Client customization through `McpSyncClientCustomizer` or `McpAsyncClientCustomizer`
  3864. * Multiple clients with multiple transport types: `STDIO` and `SSE` (Server-Sent Events)
  3865. * Integration with Spring AI's tool execution framework
  3866. * Automatic client initialization and lifecycle management
  3867. For WebFlux-based applications, you can use the WebFlux starter instead:
  3868. ```xml
  3869. <dependency>
  3870. <groupId>org.springframework.ai</groupId>
  3871. <artifactId>spring-ai-mcp-client-webflux-spring-boot-starter</artifactId>
  3872. </dependency>
  3873. ```
  3874. This provides similar functionality but uses a WebFlux-based SSE transport implementation, recommended for production deployments.
  3875. </Tab>
  3876. <Tab title="Kotlin">
  3877. [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/kotlin-mcp-client)
  3878. ## System Requirements
  3879. Before starting, ensure your system meets these requirements:
  3880. * Java 17 or higher
  3881. * Anthropic API key (Claude)
  3882. ## Setting up your environment
  3883. First, let's install `java` and `gradle` if you haven't already.
  3884. You can download `java` from [official Oracle JDK website](https://www.oracle.com/java/technologies/downloads/).
  3885. Verify your `java` installation:
  3886. ```bash
  3887. java --version
  3888. ```
  3889. Now, let's create and set up your project:
  3890. <CodeGroup>
  3891. ```bash MacOS/Linux
  3892. # Create a new directory for our project
  3893. mkdir kotlin-mcp-client
  3894. cd kotlin-mcp-client
  3895. # Initialize a new kotlin project
  3896. gradle init
  3897. ```
  3898. ```powershell Windows
  3899. # Create a new directory for our project
  3900. md kotlin-mcp-client
  3901. cd kotlin-mcp-client
  3902. # Initialize a new kotlin project
  3903. gradle init
  3904. ```
  3905. </CodeGroup>
  3906. After running `gradle init`, you will be presented with options for creating your project.
  3907. Select **Application** as the project type, **Kotlin** as the programming language, and **Java 17** as the Java version.
  3908. Alternatively, you can create a Kotlin application using the [IntelliJ IDEA project wizard](https://kotlinlang.org/docs/jvm-get-started.html).
  3909. After creating the project, add the following dependencies:
  3910. <CodeGroup>
  3911. ```kotlin build.gradle.kts
  3912. val mcpVersion = "0.4.0"
  3913. val slf4jVersion = "2.0.9"
  3914. val anthropicVersion = "0.8.0"
  3915. dependencies {
  3916. implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion")
  3917. implementation("org.slf4j:slf4j-nop:$slf4jVersion")
  3918. implementation("com.anthropic:anthropic-java:$anthropicVersion")
  3919. }
  3920. ```
  3921. ```groovy build.gradle
  3922. def mcpVersion = '0.3.0'
  3923. def slf4jVersion = '2.0.9'
  3924. def anthropicVersion = '0.8.0'
  3925. dependencies {
  3926. implementation "io.modelcontextprotocol:kotlin-sdk:$mcpVersion"
  3927. implementation "org.slf4j:slf4j-nop:$slf4jVersion"
  3928. implementation "com.anthropic:anthropic-java:$anthropicVersion"
  3929. }
  3930. ```
  3931. </CodeGroup>
  3932. Also, add the following plugins to your build script:
  3933. <CodeGroup>
  3934. ```kotlin build.gradle.kts
  3935. plugins {
  3936. id("com.github.johnrengelman.shadow") version "8.1.1"
  3937. }
  3938. ```
  3939. ```groovy build.gradle
  3940. plugins {
  3941. id 'com.github.johnrengelman.shadow' version '8.1.1'
  3942. }
  3943. ```
  3944. </CodeGroup>
  3945. ## Setting up your API key
  3946. You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
  3947. Set up your API key:
  3948. ```bash
  3949. export ANTHROPIC_API_KEY='your-anthropic-api-key-here'
  3950. ```
  3951. <Warning>
  3952. Make sure your keep your `ANTHROPIC_API_KEY` secure!
  3953. </Warning>
  3954. ## Creating the Client
  3955. ### Basic Client Structure
  3956. First, let's create the basic client class:
  3957. ```kotlin
  3958. class MCPClient : AutoCloseable {
  3959. private val anthropic = AnthropicOkHttpClient.fromEnv()
  3960. private val mcp: Client = Client(clientInfo = Implementation(name = "mcp-client-cli", version = "1.0.0"))
  3961. private lateinit var tools: List<ToolUnion>
  3962. // methods will go here
  3963. override fun close() {
  3964. runBlocking {
  3965. mcp.close()
  3966. anthropic.close()
  3967. }
  3968. }
  3969. ```
  3970. ### Server connection management
  3971. Next, we'll implement the method to connect to an MCP server:
  3972. ```kotlin
  3973. suspend fun connectToServer(serverScriptPath: String) {
  3974. try {
  3975. val command = buildList {
  3976. when (serverScriptPath.substringAfterLast(".")) {
  3977. "js" -> add("node")
  3978. "py" -> add(if (System.getProperty("os.name").lowercase().contains("win")) "python" else "python3")
  3979. "jar" -> addAll(listOf("java", "-jar"))
  3980. else -> throw IllegalArgumentException("Server script must be a .js, .py or .jar file")
  3981. }
  3982. add(serverScriptPath)
  3983. }
  3984. val process = ProcessBuilder(command).start()
  3985. val transport = StdioClientTransport(
  3986. input = process.inputStream.asSource().buffered(),
  3987. output = process.outputStream.asSink().buffered()
  3988. )
  3989. mcp.connect(transport)
  3990. val toolsResult = mcp.listTools()
  3991. tools = toolsResult?.tools?.map { tool ->
  3992. ToolUnion.ofTool(
  3993. Tool.builder()
  3994. .name(tool.name)
  3995. .description(tool.description ?: "")
  3996. .inputSchema(
  3997. Tool.InputSchema.builder()
  3998. .type(JsonValue.from(tool.inputSchema.type))
  3999. .properties(tool.inputSchema.properties.toJsonValue())
  4000. .putAdditionalProperty("required", JsonValue.from(tool.inputSchema.required))
  4001. .build()
  4002. )
  4003. .build()
  4004. )
  4005. } ?: emptyList()
  4006. println("Connected to server with tools: ${tools.joinToString(", ") { it.tool().get().name() }}")
  4007. } catch (e: Exception) {
  4008. println("Failed to connect to MCP server: $e")
  4009. throw e
  4010. }
  4011. }
  4012. ```
  4013. Also create a helper function to convert from `JsonObject` to `JsonValue` for Anthropic:
  4014. ```kotlin
  4015. private fun JsonObject.toJsonValue(): JsonValue {
  4016. val mapper = ObjectMapper()
  4017. val node = mapper.readTree(this.toString())
  4018. return JsonValue.fromJsonNode(node)
  4019. }
  4020. ```
  4021. ### Query processing logic
  4022. Now let's add the core functionality for processing queries and handling tool calls:
  4023. ```kotlin
  4024. private val messageParamsBuilder: MessageCreateParams.Builder = MessageCreateParams.builder()
  4025. .model(Model.CLAUDE_3_5_SONNET_20241022)
  4026. .maxTokens(1024)
  4027. suspend fun processQuery(query: String): String {
  4028. val messages = mutableListOf(
  4029. MessageParam.builder()
  4030. .role(MessageParam.Role.USER)
  4031. .content(query)
  4032. .build()
  4033. )
  4034. val response = anthropic.messages().create(
  4035. messageParamsBuilder
  4036. .messages(messages)
  4037. .tools(tools)
  4038. .build()
  4039. )
  4040. val finalText = mutableListOf<String>()
  4041. response.content().forEach { content ->
  4042. when {
  4043. content.isText() -> finalText.add(content.text().getOrNull()?.text() ?: "")
  4044. content.isToolUse() -> {
  4045. val toolName = content.toolUse().get().name()
  4046. val toolArgs =
  4047. content.toolUse().get()._input().convert(object : TypeReference<Map<String, JsonValue>>() {})
  4048. val result = mcp.callTool(
  4049. name = toolName,
  4050. arguments = toolArgs ?: emptyMap()
  4051. )
  4052. finalText.add("[Calling tool $toolName with args $toolArgs]")
  4053. messages.add(
  4054. MessageParam.builder()
  4055. .role(MessageParam.Role.USER)
  4056. .content(
  4057. """
  4058. "type": "tool_result",
  4059. "tool_name": $toolName,
  4060. "result": ${result?.content?.joinToString("\n") { (it as TextContent).text ?: "" }}
  4061. """.trimIndent()
  4062. )
  4063. .build()
  4064. )
  4065. val aiResponse = anthropic.messages().create(
  4066. messageParamsBuilder
  4067. .messages(messages)
  4068. .build()
  4069. )
  4070. finalText.add(aiResponse.content().first().text().getOrNull()?.text() ?: "")
  4071. }
  4072. }
  4073. }
  4074. return finalText.joinToString("\n", prefix = "", postfix = "")
  4075. }
  4076. ```
  4077. ### Interactive chat
  4078. We'll add the chat loop:
  4079. ```kotlin
  4080. suspend fun chatLoop() {
  4081. println("\nMCP Client Started!")
  4082. println("Type your queries or 'quit' to exit.")
  4083. while (true) {
  4084. print("\nQuery: ")
  4085. val message = readLine() ?: break
  4086. if (message.lowercase() == "quit") break
  4087. val response = processQuery(message)
  4088. println("\n$response")
  4089. }
  4090. }
  4091. ```
  4092. ### Main entry point
  4093. Finally, we'll add the main execution function:
  4094. ```kotlin
  4095. fun main(args: Array<String>) = runBlocking {
  4096. if (args.isEmpty()) throw IllegalArgumentException("Usage: java -jar <your_path>/build/libs/kotlin-mcp-client-0.1.0-all.jar <path_to_server_script>")
  4097. val serverPath = args.first()
  4098. val client = MCPClient()
  4099. client.use {
  4100. client.connectToServer(serverPath)
  4101. client.chatLoop()
  4102. }
  4103. }
  4104. ```
  4105. ## Running the client
  4106. To run your client with any MCP server:
  4107. ```bash
  4108. ./gradlew build
  4109. # Run the client
  4110. java -jar build/libs/<your-jar-name>.jar path/to/server.jar # jvm server
  4111. java -jar build/libs/<your-jar-name>.jar path/to/server.py # python server
  4112. java -jar build/libs/<your-jar-name>.jar path/to/build/index.js # node server
  4113. ```
  4114. <Note>
  4115. If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar .../samples/weather-stdio-server/build/libs/weather-stdio-server-0.1.0-all.jar`
  4116. </Note>
  4117. **The client will:**
  4118. 1. Connect to the specified server
  4119. 2. List available tools
  4120. 3. Start an interactive chat session where you can:
  4121. * Enter queries
  4122. * See tool executions
  4123. * Get responses from Claude
  4124. ## How it works
  4125. Here's a high-level workflow schema:
  4126. ```mermaid
  4127. ---
  4128. config:
  4129. theme: neutral
  4130. ---
  4131. sequenceDiagram
  4132. actor User
  4133. participant Client
  4134. participant Claude
  4135. participant MCP_Server as MCP Server
  4136. participant Tools
  4137. User->>Client: Send query
  4138. Client<<->>MCP_Server: Get available tools
  4139. Client->>Claude: Send query with tool descriptions
  4140. Claude-->>Client: Decide tool execution
  4141. Client->>MCP_Server: Request tool execution
  4142. MCP_Server->>Tools: Execute chosen tools
  4143. Tools-->>MCP_Server: Return results
  4144. MCP_Server-->>Client: Send results
  4145. Client->>Claude: Send tool results
  4146. Claude-->>Client: Provide final response
  4147. Client-->>User: Display response
  4148. ```
  4149. When you submit a query:
  4150. 1. The client gets the list of available tools from the server
  4151. 2. Your query is sent to Claude along with tool descriptions
  4152. 3. Claude decides which tools (if any) to use
  4153. 4. The client executes any requested tool calls through the server
  4154. 5. Results are sent back to Claude
  4155. 6. Claude provides a natural language response
  4156. 7. The response is displayed to you
  4157. ## Best practices
  4158. 1. **Error Handling**
  4159. * Leverage Kotlin's type system to model errors explicitly
  4160. * Wrap external tool and API calls in `try-catch` blocks when exceptions are possible
  4161. * Provide clear and meaningful error messages
  4162. * Handle network timeouts and connection issues gracefully
  4163. 2. **Security**
  4164. * Store API keys and secrets securely in `local.properties`, environment variables, or secret managers
  4165. * Validate all external responses to avoid unexpected or unsafe data usage
  4166. * Be cautious with permissions and trust boundaries when using tools
  4167. ## Troubleshooting
  4168. ### Server Path Issues
  4169. * Double-check the path to your server script is correct
  4170. * Use the absolute path if the relative path isn't working
  4171. * For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
  4172. * Make sure that the required runtime is installed (java for Java, npm for Node.js, or uv for Python)
  4173. * Verify the server file has the correct extension (.jar for Java, .js for Node.js or .py for Python)
  4174. Example of correct path usage:
  4175. ```bash
  4176. # Relative path
  4177. java -jar build/libs/client.jar ./server/build/libs/server.jar
  4178. # Absolute path
  4179. java -jar build/libs/client.jar /Users/username/projects/mcp-server/build/libs/server.jar
  4180. # Windows path (either format works)
  4181. java -jar build/libs/client.jar C:/projects/mcp-server/build/libs/server.jar
  4182. java -jar build/libs/client.jar C:\\projects\\mcp-server\\build\\libs\\server.jar
  4183. ```
  4184. ### Response Timing
  4185. * The first response might take up to 30 seconds to return
  4186. * This is normal and happens while:
  4187. * The server initializes
  4188. * Claude processes the query
  4189. * Tools are being executed
  4190. * Subsequent responses are typically faster
  4191. * Don't interrupt the process during this initial waiting period
  4192. ### Common Error Messages
  4193. If you see:
  4194. * `Connection refused`: Ensure the server is running and the path is correct
  4195. * `Tool execution failed`: Verify the tool's required environment variables are set
  4196. * `ANTHROPIC_API_KEY is not set`: Check your environment variables
  4197. </Tab>
  4198. <Tab title="C#">
  4199. [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/csharp-sdk/tree/main/samples/QuickstartClient)
  4200. ## System Requirements
  4201. Before starting, ensure your system meets these requirements:
  4202. * .NET 8.0 or higher
  4203. * Anthropic API key (Claude)
  4204. * Windows, Linux, or MacOS
  4205. ## Setting up your environment
  4206. First, create a new .NET project:
  4207. ```bash
  4208. dotnet new console -n QuickstartClient
  4209. cd QuickstartClient
  4210. ```
  4211. Then, add the required dependencies to your project:
  4212. ```bash
  4213. dotnet add package ModelContextProtocol --prerelease
  4214. dotnet add package Anthropic.SDK
  4215. dotnet add package Microsoft.Extensions.Hosting
  4216. ```
  4217. ## Setting up your API key
  4218. You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
  4219. ```bash
  4220. dotnet user-secrets init
  4221. dotnet user-secrets set "ANTHROPIC_API_KEY" "<your key here>"
  4222. ```
  4223. ## Creating the Client
  4224. ### Basic Client Structure
  4225. First, let's setup the basic client class in the file `Program.cs`:
  4226. ```csharp
  4227. using Anthropic.SDK;
  4228. using Microsoft.Extensions.AI;
  4229. using Microsoft.Extensions.Configuration;
  4230. using Microsoft.Extensions.Hosting;
  4231. using ModelContextProtocol.Client;
  4232. using ModelContextProtocol.Protocol.Transport;
  4233. var builder = Host.CreateApplicationBuilder(args);
  4234. builder.Configuration
  4235. .AddEnvironmentVariables()
  4236. .AddUserSecrets<Program>();
  4237. ```
  4238. This creates the beginnings of a .NET console application that can read the API key from user secrets.
  4239. Next, we'll setup the MCP Client:
  4240. ```csharp
  4241. var (command, arguments) = GetCommandAndArguments(args);
  4242. var clientTransport = new StdioClientTransport(new()
  4243. {
  4244. Name = "Demo Server",
  4245. Command = command,
  4246. Arguments = arguments,
  4247. });
  4248. await using var mcpClient = await McpClientFactory.CreateAsync(clientTransport);
  4249. var tools = await mcpClient.ListToolsAsync();
  4250. foreach (var tool in tools)
  4251. {
  4252. Console.WriteLine($"Connected to server with tools: {tool.Name}");
  4253. }
  4254. ```
  4255. Add this function at the end of the `Program.cs` file:
  4256. ```csharp
  4257. static (string command, string[] arguments) GetCommandAndArguments(string[] args)
  4258. {
  4259. return args switch
  4260. {
  4261. [var script] when script.EndsWith(".py") => ("python", args),
  4262. [var script] when script.EndsWith(".js") => ("node", args),
  4263. [var script] when Directory.Exists(script) || (File.Exists(script) && script.EndsWith(".csproj")) => ("dotnet", ["run", "--project", script, "--no-build"]),
  4264. _ => throw new NotSupportedException("An unsupported server script was provided. Supported scripts are .py, .js, or .csproj")
  4265. };
  4266. }
  4267. ```
  4268. This creates a MCP client that will connect to a server that is provided as a command line argument. It then lists the available tools from the connected server.
  4269. ### Query processing logic
  4270. Now let's add the core functionality for processing queries and handling tool calls:
  4271. ```csharp
  4272. using var anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration["ANTHROPIC_API_KEY"]))
  4273. .Messages
  4274. .AsBuilder()
  4275. .UseFunctionInvocation()
  4276. .Build();
  4277. var options = new ChatOptions
  4278. {
  4279. MaxOutputTokens = 1000,
  4280. ModelId = "claude-3-5-sonnet-20241022",
  4281. Tools = [.. tools]
  4282. };
  4283. Console.ForegroundColor = ConsoleColor.Green;
  4284. Console.WriteLine("MCP Client Started!");
  4285. Console.ResetColor();
  4286. PromptForInput();
  4287. while(Console.ReadLine() is string query && !"exit".Equals(query, StringComparison.OrdinalIgnoreCase))
  4288. {
  4289. if (string.IsNullOrWhiteSpace(query))
  4290. {
  4291. PromptForInput();
  4292. continue;
  4293. }
  4294. await foreach (var message in anthropicClient.GetStreamingResponseAsync(query, options))
  4295. {
  4296. Console.Write(message);
  4297. }
  4298. Console.WriteLine();
  4299. PromptForInput();
  4300. }
  4301. static void PromptForInput()
  4302. {
  4303. Console.WriteLine("Enter a command (or 'exit' to quit):");
  4304. Console.ForegroundColor = ConsoleColor.Cyan;
  4305. Console.Write("> ");
  4306. Console.ResetColor();
  4307. }
  4308. ```
  4309. ## Key Components Explained
  4310. ### 1. Client Initialization
  4311. * The client is initialized using `McpClientFactory.CreateAsync()`, which sets up the transport type and command to run the server.
  4312. ### 2. Server Connection
  4313. * Supports Python, Node.js, and .NET servers.
  4314. * The server is started using the command specified in the arguments.
  4315. * Configures to use stdio for communication with the server.
  4316. * Initializes the session and available tools.
  4317. ### 3. Query Processing
  4318. * Leverages [Microsoft.Extensions.AI](https://learn.microsoft.com/dotnet/ai/ai-extensions) for the chat client.
  4319. * Configures the `IChatClient` to use automatic tool (function) invocation.
  4320. * The client reads user input and sends it to the server.
  4321. * The server processes the query and returns a response.
  4322. * The response is displayed to the user.
  4323. ## Running the Client
  4324. To run your client with any MCP server:
  4325. ```bash
  4326. dotnet run -- path/to/server.csproj # dotnet server
  4327. dotnet run -- path/to/server.py # python server
  4328. dotnet run -- path/to/server.js # node server
  4329. ```
  4330. <Note>
  4331. If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `dotnet run -- path/to/QuickstartWeatherServer`.
  4332. </Note>
  4333. The client will:
  4334. 1. Connect to the specified server
  4335. 2. List available tools
  4336. 3. Start an interactive chat session where you can:
  4337. * Enter queries
  4338. * See tool executions
  4339. * Get responses from Claude
  4340. 4. Exit the session when done
  4341. Here's an example of what it should look like it connected to a weather server quickstart:
  4342. <Frame>
  4343. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-dotnet-client.png" />
  4344. </Frame>
  4345. </Tab>
  4346. </Tabs>
  4347. ## Next steps
  4348. <CardGroup cols={2}>
  4349. <Card title="Example servers" icon="grid" href="/examples">
  4350. Check out our gallery of official MCP servers and implementations
  4351. </Card>
  4352. <Card title="Clients" icon="cubes" href="/clients">
  4353. View the list of clients that support MCP integrations
  4354. </Card>
  4355. <Card title="Building MCP with LLMs" icon="comments" href="/tutorials/building-mcp-with-llms">
  4356. Learn how to use LLMs like Claude to speed up your MCP development
  4357. </Card>
  4358. <Card title="Core architecture" icon="sitemap" href="/docs/concepts/architecture">
  4359. Understand how MCP connects clients, servers, and LLMs
  4360. </Card>
  4361. </CardGroup>
  4362. # For Server Developers
  4363. Source: https://modelcontextprotocol.io/quickstart/server
  4364. Get started building your own server to use in Claude for Desktop and other clients.
  4365. In this tutorial, we'll build a simple MCP weather server and connect it to a host, Claude for Desktop. We'll start with a basic setup, and then progress to more complex use cases.
  4366. ### What we'll be building
  4367. Many LLMs do not currently have the ability to fetch the forecast and severe weather alerts. Let's use MCP to solve that!
  4368. We'll build a server that exposes two tools: `get-alerts` and `get-forecast`. Then we'll connect the server to an MCP host (in this case, Claude for Desktop):
  4369. <Frame>
  4370. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/weather-alerts.png" />
  4371. </Frame>
  4372. <Frame>
  4373. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/current-weather.png" />
  4374. </Frame>
  4375. <Note>
  4376. Servers can connect to any client. We've chosen Claude for Desktop here for simplicity, but we also have guides on [building your own client](/quickstart/client) as well as a [list of other clients here](/clients).
  4377. </Note>
  4378. <Accordion title="Why Claude for Desktop and not Claude.ai?">
  4379. Because servers are locally run, MCP currently only supports desktop hosts. Remote hosts are in active development.
  4380. </Accordion>
  4381. ### Core MCP Concepts
  4382. MCP servers can provide three main types of capabilities:
  4383. 1. **Resources**: File-like data that can be read by clients (like API responses or file contents)
  4384. 2. **Tools**: Functions that can be called by the LLM (with user approval)
  4385. 3. **Prompts**: Pre-written templates that help users accomplish specific tasks
  4386. This tutorial will primarily focus on tools.
  4387. <Tabs>
  4388. <Tab title="Python">
  4389. Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python)
  4390. ### Prerequisite knowledge
  4391. This quickstart assumes you have familiarity with:
  4392. * Python
  4393. * LLMs like Claude
  4394. ### System requirements
  4395. * Python 3.10 or higher installed.
  4396. * You must use the Python MCP SDK 1.2.0 or higher.
  4397. ### Set up your environment
  4398. First, let's install `uv` and set up our Python project and environment:
  4399. <CodeGroup>
  4400. ```bash MacOS/Linux
  4401. curl -LsSf https://astral.sh/uv/install.sh | sh
  4402. ```
  4403. ```powershell Windows
  4404. powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
  4405. ```
  4406. </CodeGroup>
  4407. Make sure to restart your terminal afterwards to ensure that the `uv` command gets picked up.
  4408. Now, let's create and set up our project:
  4409. <CodeGroup>
  4410. ```bash MacOS/Linux
  4411. # Create a new directory for our project
  4412. uv init weather
  4413. cd weather
  4414. # Create virtual environment and activate it
  4415. uv venv
  4416. source .venv/bin/activate
  4417. # Install dependencies
  4418. uv add "mcp[cli]" httpx
  4419. # Create our server file
  4420. touch weather.py
  4421. ```
  4422. ```powershell Windows
  4423. # Create a new directory for our project
  4424. uv init weather
  4425. cd weather
  4426. # Create virtual environment and activate it
  4427. uv venv
  4428. .venv\Scripts\activate
  4429. # Install dependencies
  4430. uv add mcp[cli] httpx
  4431. # Create our server file
  4432. new-item weather.py
  4433. ```
  4434. </CodeGroup>
  4435. Now let's dive into building your server.
  4436. ## Building your server
  4437. ### Importing packages and setting up the instance
  4438. Add these to the top of your `weather.py`:
  4439. ```python
  4440. from typing import Any
  4441. import httpx
  4442. from mcp.server.fastmcp import FastMCP
  4443. # Initialize FastMCP server
  4444. mcp = FastMCP("weather")
  4445. # Constants
  4446. NWS_API_BASE = "https://api.weather.gov"
  4447. USER_AGENT = "weather-app/1.0"
  4448. ```
  4449. The FastMCP class uses Python type hints and docstrings to automatically generate tool definitions, making it easy to create and maintain MCP tools.
  4450. ### Helper functions
  4451. Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
  4452. ```python
  4453. async def make_nws_request(url: str) -> dict[str, Any] | None:
  4454. """Make a request to the NWS API with proper error handling."""
  4455. headers = {
  4456. "User-Agent": USER_AGENT,
  4457. "Accept": "application/geo+json"
  4458. }
  4459. async with httpx.AsyncClient() as client:
  4460. try:
  4461. response = await client.get(url, headers=headers, timeout=30.0)
  4462. response.raise_for_status()
  4463. return response.json()
  4464. except Exception:
  4465. return None
  4466. def format_alert(feature: dict) -> str:
  4467. """Format an alert feature into a readable string."""
  4468. props = feature["properties"]
  4469. return f"""
  4470. Event: {props.get('event', 'Unknown')}
  4471. Area: {props.get('areaDesc', 'Unknown')}
  4472. Severity: {props.get('severity', 'Unknown')}
  4473. Description: {props.get('description', 'No description available')}
  4474. Instructions: {props.get('instruction', 'No specific instructions provided')}
  4475. """
  4476. ```
  4477. ### Implementing tool execution
  4478. The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
  4479. ```python
  4480. @mcp.tool()
  4481. async def get_alerts(state: str) -> str:
  4482. """Get weather alerts for a US state.
  4483. Args:
  4484. state: Two-letter US state code (e.g. CA, NY)
  4485. """
  4486. url = f"{NWS_API_BASE}/alerts/active/area/{state}"
  4487. data = await make_nws_request(url)
  4488. if not data or "features" not in data:
  4489. return "Unable to fetch alerts or no alerts found."
  4490. if not data["features"]:
  4491. return "No active alerts for this state."
  4492. alerts = [format_alert(feature) for feature in data["features"]]
  4493. return "\n---\n".join(alerts)
  4494. @mcp.tool()
  4495. async def get_forecast(latitude: float, longitude: float) -> str:
  4496. """Get weather forecast for a location.
  4497. Args:
  4498. latitude: Latitude of the location
  4499. longitude: Longitude of the location
  4500. """
  4501. # First get the forecast grid endpoint
  4502. points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
  4503. points_data = await make_nws_request(points_url)
  4504. if not points_data:
  4505. return "Unable to fetch forecast data for this location."
  4506. # Get the forecast URL from the points response
  4507. forecast_url = points_data["properties"]["forecast"]
  4508. forecast_data = await make_nws_request(forecast_url)
  4509. if not forecast_data:
  4510. return "Unable to fetch detailed forecast."
  4511. # Format the periods into a readable forecast
  4512. periods = forecast_data["properties"]["periods"]
  4513. forecasts = []
  4514. for period in periods[:5]: # Only show next 5 periods
  4515. forecast = f"""
  4516. {period['name']}:
  4517. Temperature: {period['temperature']}°{period['temperatureUnit']}
  4518. Wind: {period['windSpeed']} {period['windDirection']}
  4519. Forecast: {period['detailedForecast']}
  4520. """
  4521. forecasts.append(forecast)
  4522. return "\n---\n".join(forecasts)
  4523. ```
  4524. ### Running the server
  4525. Finally, let's initialize and run the server:
  4526. ```python
  4527. if __name__ == "__main__":
  4528. # Initialize and run the server
  4529. mcp.run(transport='stdio')
  4530. ```
  4531. Your server is complete! Run `uv run weather.py` to confirm that everything's working.
  4532. Let's now test your server from an existing MCP host, Claude for Desktop.
  4533. ## Testing your server with Claude for Desktop
  4534. <Note>
  4535. Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/quickstart/client) tutorial to build an MCP client that connects to the server we just built.
  4536. </Note>
  4537. First, make sure you have Claude for Desktop installed. [You can install the latest version
  4538. here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
  4539. We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
  4540. For example, if you have [VS Code](https://code.visualstudio.com/) installed:
  4541. <Tabs>
  4542. <Tab title="MacOS/Linux">
  4543. ```bash
  4544. code ~/Library/Application\ Support/Claude/claude_desktop_config.json
  4545. ```
  4546. </Tab>
  4547. <Tab title="Windows">
  4548. ```powershell
  4549. code $env:AppData\Claude\claude_desktop_config.json
  4550. ```
  4551. </Tab>
  4552. </Tabs>
  4553. You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
  4554. In this case, we'll add our single weather server like so:
  4555. <Tabs>
  4556. <Tab title="MacOS/Linux">
  4557. ```json Python
  4558. {
  4559. "mcpServers": {
  4560. "weather": {
  4561. "command": "uv",
  4562. "args": [
  4563. "--directory",
  4564. "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
  4565. "run",
  4566. "weather.py"
  4567. ]
  4568. }
  4569. }
  4570. }
  4571. ```
  4572. </Tab>
  4573. <Tab title="Windows">
  4574. ```json Python
  4575. {
  4576. "mcpServers": {
  4577. "weather": {
  4578. "command": "uv",
  4579. "args": [
  4580. "--directory",
  4581. "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather",
  4582. "run",
  4583. "weather.py"
  4584. ]
  4585. }
  4586. }
  4587. }
  4588. ```
  4589. </Tab>
  4590. </Tabs>
  4591. <Warning>
  4592. You may need to put the full path to the `uv` executable in the `command` field. You can get this by running `which uv` on MacOS/Linux or `where uv` on Windows.
  4593. </Warning>
  4594. <Note>
  4595. Make sure you pass in the absolute path to your server.
  4596. </Note>
  4597. This tells Claude for Desktop:
  4598. 1. There's an MCP server named "weather"
  4599. 2. To launch it by running `uv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather.py`
  4600. Save the file, and restart **Claude for Desktop**.
  4601. </Tab>
  4602. <Tab title="Node">
  4603. Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript)
  4604. ### Prerequisite knowledge
  4605. This quickstart assumes you have familiarity with:
  4606. * TypeScript
  4607. * LLMs like Claude
  4608. ### System requirements
  4609. For TypeScript, make sure you have the latest version of Node installed.
  4610. ### Set up your environment
  4611. First, let's install Node.js and npm if you haven't already. You can download them from [nodejs.org](https://nodejs.org/).
  4612. Verify your Node.js installation:
  4613. ```bash
  4614. node --version
  4615. npm --version
  4616. ```
  4617. For this tutorial, you'll need Node.js version 16 or higher.
  4618. Now, let's create and set up our project:
  4619. <CodeGroup>
  4620. ```bash MacOS/Linux
  4621. # Create a new directory for our project
  4622. mkdir weather
  4623. cd weather
  4624. # Initialize a new npm project
  4625. npm init -y
  4626. # Install dependencies
  4627. npm install @modelcontextprotocol/sdk zod
  4628. npm install -D @types/node typescript
  4629. # Create our files
  4630. mkdir src
  4631. touch src/index.ts
  4632. ```
  4633. ```powershell Windows
  4634. # Create a new directory for our project
  4635. md weather
  4636. cd weather
  4637. # Initialize a new npm project
  4638. npm init -y
  4639. # Install dependencies
  4640. npm install @modelcontextprotocol/sdk zod
  4641. npm install -D @types/node typescript
  4642. # Create our files
  4643. md src
  4644. new-item src\index.ts
  4645. ```
  4646. </CodeGroup>
  4647. Update your package.json to add type: "module" and a build script:
  4648. ```json package.json
  4649. {
  4650. "type": "module",
  4651. "bin": {
  4652. "weather": "./build/index.js"
  4653. },
  4654. "scripts": {
  4655. "build": "tsc && chmod 755 build/index.js"
  4656. },
  4657. "files": ["build"]
  4658. }
  4659. ```
  4660. Create a `tsconfig.json` in the root of your project:
  4661. ```json tsconfig.json
  4662. {
  4663. "compilerOptions": {
  4664. "target": "ES2022",
  4665. "module": "Node16",
  4666. "moduleResolution": "Node16",
  4667. "outDir": "./build",
  4668. "rootDir": "./src",
  4669. "strict": true,
  4670. "esModuleInterop": true,
  4671. "skipLibCheck": true,
  4672. "forceConsistentCasingInFileNames": true
  4673. },
  4674. "include": ["src/**/*"],
  4675. "exclude": ["node_modules"]
  4676. }
  4677. ```
  4678. Now let's dive into building your server.
  4679. ## Building your server
  4680. ### Importing packages and setting up the instance
  4681. Add these to the top of your `src/index.ts`:
  4682. ```typescript
  4683. import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
  4684. import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
  4685. import { z } from "zod";
  4686. const NWS_API_BASE = "https://api.weather.gov";
  4687. const USER_AGENT = "weather-app/1.0";
  4688. // Create server instance
  4689. const server = new McpServer({
  4690. name: "weather",
  4691. version: "1.0.0",
  4692. capabilities: {
  4693. resources: {},
  4694. tools: {},
  4695. },
  4696. });
  4697. ```
  4698. ### Helper functions
  4699. Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
  4700. ```typescript
  4701. // Helper function for making NWS API requests
  4702. async function makeNWSRequest<T>(url: string): Promise<T | null> {
  4703. const headers = {
  4704. "User-Agent": USER_AGENT,
  4705. Accept: "application/geo+json",
  4706. };
  4707. try {
  4708. const response = await fetch(url, { headers });
  4709. if (!response.ok) {
  4710. throw new Error(`HTTP error! status: ${response.status}`);
  4711. }
  4712. return (await response.json()) as T;
  4713. } catch (error) {
  4714. console.error("Error making NWS request:", error);
  4715. return null;
  4716. }
  4717. }
  4718. interface AlertFeature {
  4719. properties: {
  4720. event?: string;
  4721. areaDesc?: string;
  4722. severity?: string;
  4723. status?: string;
  4724. headline?: string;
  4725. };
  4726. }
  4727. // Format alert data
  4728. function formatAlert(feature: AlertFeature): string {
  4729. const props = feature.properties;
  4730. return [
  4731. `Event: ${props.event || "Unknown"}`,
  4732. `Area: ${props.areaDesc || "Unknown"}`,
  4733. `Severity: ${props.severity || "Unknown"}`,
  4734. `Status: ${props.status || "Unknown"}`,
  4735. `Headline: ${props.headline || "No headline"}`,
  4736. "---",
  4737. ].join("\n");
  4738. }
  4739. interface ForecastPeriod {
  4740. name?: string;
  4741. temperature?: number;
  4742. temperatureUnit?: string;
  4743. windSpeed?: string;
  4744. windDirection?: string;
  4745. shortForecast?: string;
  4746. }
  4747. interface AlertsResponse {
  4748. features: AlertFeature[];
  4749. }
  4750. interface PointsResponse {
  4751. properties: {
  4752. forecast?: string;
  4753. };
  4754. }
  4755. interface ForecastResponse {
  4756. properties: {
  4757. periods: ForecastPeriod[];
  4758. };
  4759. }
  4760. ```
  4761. ### Implementing tool execution
  4762. The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
  4763. ```typescript
  4764. // Register weather tools
  4765. server.tool(
  4766. "get-alerts",
  4767. "Get weather alerts for a state",
  4768. {
  4769. state: z.string().length(2).describe("Two-letter state code (e.g. CA, NY)"),
  4770. },
  4771. async ({ state }) => {
  4772. const stateCode = state.toUpperCase();
  4773. const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`;
  4774. const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl);
  4775. if (!alertsData) {
  4776. return {
  4777. content: [
  4778. {
  4779. type: "text",
  4780. text: "Failed to retrieve alerts data",
  4781. },
  4782. ],
  4783. };
  4784. }
  4785. const features = alertsData.features || [];
  4786. if (features.length === 0) {
  4787. return {
  4788. content: [
  4789. {
  4790. type: "text",
  4791. text: `No active alerts for ${stateCode}`,
  4792. },
  4793. ],
  4794. };
  4795. }
  4796. const formattedAlerts = features.map(formatAlert);
  4797. const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join("\n")}`;
  4798. return {
  4799. content: [
  4800. {
  4801. type: "text",
  4802. text: alertsText,
  4803. },
  4804. ],
  4805. };
  4806. },
  4807. );
  4808. server.tool(
  4809. "get-forecast",
  4810. "Get weather forecast for a location",
  4811. {
  4812. latitude: z.number().min(-90).max(90).describe("Latitude of the location"),
  4813. longitude: z
  4814. .number()
  4815. .min(-180)
  4816. .max(180)
  4817. .describe("Longitude of the location"),
  4818. },
  4819. async ({ latitude, longitude }) => {
  4820. // Get grid point data
  4821. const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`;
  4822. const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl);
  4823. if (!pointsData) {
  4824. return {
  4825. content: [
  4826. {
  4827. type: "text",
  4828. text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`,
  4829. },
  4830. ],
  4831. };
  4832. }
  4833. const forecastUrl = pointsData.properties?.forecast;
  4834. if (!forecastUrl) {
  4835. return {
  4836. content: [
  4837. {
  4838. type: "text",
  4839. text: "Failed to get forecast URL from grid point data",
  4840. },
  4841. ],
  4842. };
  4843. }
  4844. // Get forecast data
  4845. const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl);
  4846. if (!forecastData) {
  4847. return {
  4848. content: [
  4849. {
  4850. type: "text",
  4851. text: "Failed to retrieve forecast data",
  4852. },
  4853. ],
  4854. };
  4855. }
  4856. const periods = forecastData.properties?.periods || [];
  4857. if (periods.length === 0) {
  4858. return {
  4859. content: [
  4860. {
  4861. type: "text",
  4862. text: "No forecast periods available",
  4863. },
  4864. ],
  4865. };
  4866. }
  4867. // Format forecast periods
  4868. const formattedForecast = periods.map((period: ForecastPeriod) =>
  4869. [
  4870. `${period.name || "Unknown"}:`,
  4871. `Temperature: ${period.temperature || "Unknown"}°${period.temperatureUnit || "F"}`,
  4872. `Wind: ${period.windSpeed || "Unknown"} ${period.windDirection || ""}`,
  4873. `${period.shortForecast || "No forecast available"}`,
  4874. "---",
  4875. ].join("\n"),
  4876. );
  4877. const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join("\n")}`;
  4878. return {
  4879. content: [
  4880. {
  4881. type: "text",
  4882. text: forecastText,
  4883. },
  4884. ],
  4885. };
  4886. },
  4887. );
  4888. ```
  4889. ### Running the server
  4890. Finally, implement the main function to run the server:
  4891. ```typescript
  4892. async function main() {
  4893. const transport = new StdioServerTransport();
  4894. await server.connect(transport);
  4895. console.error("Weather MCP Server running on stdio");
  4896. }
  4897. main().catch((error) => {
  4898. console.error("Fatal error in main():", error);
  4899. process.exit(1);
  4900. });
  4901. ```
  4902. Make sure to run `npm run build` to build your server! This is a very important step in getting your server to connect.
  4903. Let's now test your server from an existing MCP host, Claude for Desktop.
  4904. ## Testing your server with Claude for Desktop
  4905. <Note>
  4906. Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/quickstart/client) tutorial to build an MCP client that connects to the server we just built.
  4907. </Note>
  4908. First, make sure you have Claude for Desktop installed. [You can install the latest version
  4909. here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
  4910. We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
  4911. For example, if you have [VS Code](https://code.visualstudio.com/) installed:
  4912. <Tabs>
  4913. <Tab title="MacOS/Linux">
  4914. ```bash
  4915. code ~/Library/Application\ Support/Claude/claude_desktop_config.json
  4916. ```
  4917. </Tab>
  4918. <Tab title="Windows">
  4919. ```powershell
  4920. code $env:AppData\Claude\claude_desktop_config.json
  4921. ```
  4922. </Tab>
  4923. </Tabs>
  4924. You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
  4925. In this case, we'll add our single weather server like so:
  4926. <Tabs>
  4927. <Tab title="MacOS/Linux">
  4928. <CodeGroup>
  4929. ```json Node
  4930. {
  4931. "mcpServers": {
  4932. "weather": {
  4933. "command": "node",
  4934. "args": ["/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js"]
  4935. }
  4936. }
  4937. }
  4938. ```
  4939. </CodeGroup>
  4940. </Tab>
  4941. <Tab title="Windows">
  4942. <CodeGroup>
  4943. ```json Node
  4944. {
  4945. "mcpServers": {
  4946. "weather": {
  4947. "command": "node",
  4948. "args": ["C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\index.js"]
  4949. }
  4950. }
  4951. }
  4952. ```
  4953. </CodeGroup>
  4954. </Tab>
  4955. </Tabs>
  4956. This tells Claude for Desktop:
  4957. 1. There's an MCP server named "weather"
  4958. 2. Launch it by running `node /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js`
  4959. Save the file, and restart **Claude for Desktop**.
  4960. </Tab>
  4961. <Tab title="Java">
  4962. <Note>
  4963. This is a quickstart demo based on Spring AI MCP auto-configuration and boot starters.
  4964. To learn how to create sync and async MCP Servers, manually, consult the [Java SDK Server](/sdk/java/mcp-server) documentation.
  4965. </Note>
  4966. Let's get started with building our weather server!
  4967. [You can find the complete code for what we'll be building here.](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-stdio-server)
  4968. For more information, see the [MCP Server Boot Starter](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html) reference documentation.
  4969. For manual MCP Server implementation, refer to the [MCP Server Java SDK documentation](/sdk/java/mcp-server).
  4970. ### System requirements
  4971. * Java 17 or higher installed.
  4972. * [Spring Boot 3.3.x](https://docs.spring.io/spring-boot/installing.html) or higher
  4973. ### Set up your environment
  4974. Use the [Spring Initializer](https://start.spring.io/) to bootstrap the project.
  4975. You will need to add the following dependencies:
  4976. <Tabs>
  4977. <Tab title="Maven">
  4978. ```xml
  4979. <dependencies>
  4980. <dependency>
  4981. <groupId>org.springframework.ai</groupId>
  4982. <artifactId>spring-ai-starter-mcp-server</artifactId>
  4983. </dependency>
  4984. <dependency>
  4985. <groupId>org.springframework</groupId>
  4986. <artifactId>spring-web</artifactId>
  4987. </dependency>
  4988. </dependencies>
  4989. ```
  4990. </Tab>
  4991. <Tab title="Gradle">
  4992. ```groovy
  4993. dependencies {
  4994. implementation platform("org.springframework.ai:spring-ai-starter-mcp-server")
  4995. implementation platform("org.springframework:spring-web")
  4996. }
  4997. ```
  4998. </Tab>
  4999. </Tabs>
  5000. Then configure your application by setting the application properties:
  5001. <CodeGroup>
  5002. ```bash application.properties
  5003. spring.main.bannerMode=off
  5004. logging.pattern.console=
  5005. ```
  5006. ```yaml application.yml
  5007. logging:
  5008. pattern:
  5009. console:
  5010. spring:
  5011. main:
  5012. banner-mode: off
  5013. ```
  5014. </CodeGroup>
  5015. The [Server Configuration Properties](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html#_configuration_properties) documents all available properties.
  5016. Now let's dive into building your server.
  5017. ## Building your server
  5018. ### Weather Service
  5019. Let's implement a [WeatherService.java](https://github.com/spring-projects/spring-ai-examples/blob/main/model-context-protocol/weather/starter-stdio-server/src/main/java/org/springframework/ai/mcp/sample/server/WeatherService.java) that uses a REST client to query the data from the National Weather Service API:
  5020. ```java
  5021. @Service
  5022. public class WeatherService {
  5023. private final RestClient restClient;
  5024. public WeatherService() {
  5025. this.restClient = RestClient.builder()
  5026. .baseUrl("https://api.weather.gov")
  5027. .defaultHeader("Accept", "application/geo+json")
  5028. .defaultHeader("User-Agent", "WeatherApiClient/1.0 (your@email.com)")
  5029. .build();
  5030. }
  5031. @Tool(description = "Get weather forecast for a specific latitude/longitude")
  5032. public String getWeatherForecastByLocation(
  5033. double latitude, // Latitude coordinate
  5034. double longitude // Longitude coordinate
  5035. ) {
  5036. // Returns detailed forecast including:
  5037. // - Temperature and unit
  5038. // - Wind speed and direction
  5039. // - Detailed forecast description
  5040. }
  5041. @Tool(description = "Get weather alerts for a US state")
  5042. public String getAlerts(
  5043. @ToolParam(description = "Two-letter US state code (e.g. CA, NY)" String state
  5044. ) {
  5045. // Returns active alerts including:
  5046. // - Event type
  5047. // - Affected area
  5048. // - Severity
  5049. // - Description
  5050. // - Safety instructions
  5051. }
  5052. // ......
  5053. }
  5054. ```
  5055. The `@Service` annotation with auto-register the service in your application context.
  5056. The Spring AI `@Tool` annotation, making it easy to create and maintain MCP tools.
  5057. The auto-configuration will automatically register these tools with the MCP server.
  5058. ### Create your Boot Application
  5059. ```java
  5060. @SpringBootApplication
  5061. public class McpServerApplication {
  5062. public static void main(String[] args) {
  5063. SpringApplication.run(McpServerApplication.class, args);
  5064. }
  5065. @Bean
  5066. public ToolCallbackProvider weatherTools(WeatherService weatherService) {
  5067. return MethodToolCallbackProvider.builder().toolObjects(weatherService).build();
  5068. }
  5069. }
  5070. ```
  5071. Uses the the `MethodToolCallbackProvider` utils to convert the `@Tools` into actionable callbacks used by the MCP server.
  5072. ### Running the server
  5073. Finally, let's build the server:
  5074. ```bash
  5075. ./mvnw clean install
  5076. ```
  5077. This will generate a `mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar` file within the `target` folder.
  5078. Let's now test your server from an existing MCP host, Claude for Desktop.
  5079. ## Testing your server with Claude for Desktop
  5080. <Note>
  5081. Claude for Desktop is not yet available on Linux.
  5082. </Note>
  5083. First, make sure you have Claude for Desktop installed.
  5084. [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
  5085. We'll need to configure Claude for Desktop for whichever MCP servers you want to use.
  5086. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor.
  5087. Make sure to create the file if it doesn't exist.
  5088. For example, if you have [VS Code](https://code.visualstudio.com/) installed:
  5089. <Tabs>
  5090. <Tab title="MacOS/Linux">
  5091. ```bash
  5092. code ~/Library/Application\ Support/Claude/claude_desktop_config.json
  5093. ```
  5094. </Tab>
  5095. <Tab title="Windows">
  5096. ```powershell
  5097. code $env:AppData\Claude\claude_desktop_config.json
  5098. ```
  5099. </Tab>
  5100. </Tabs>
  5101. You'll then add your servers in the `mcpServers` key.
  5102. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
  5103. In this case, we'll add our single weather server like so:
  5104. <Tabs>
  5105. <Tab title="MacOS/Linux">
  5106. ```json java
  5107. {
  5108. "mcpServers": {
  5109. "spring-ai-mcp-weather": {
  5110. "command": "java",
  5111. "args": [
  5112. "-Dspring.ai.mcp.server.stdio=true",
  5113. "-jar",
  5114. "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
  5115. ]
  5116. }
  5117. }
  5118. }
  5119. ```
  5120. </Tab>
  5121. <Tab title="Windows">
  5122. ```json java
  5123. {
  5124. "mcpServers": {
  5125. "spring-ai-mcp-weather": {
  5126. "command": "java",
  5127. "args": [
  5128. "-Dspring.ai.mcp.server.transport=STDIO",
  5129. "-jar",
  5130. "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar"
  5131. ]
  5132. }
  5133. }
  5134. }
  5135. ```
  5136. </Tab>
  5137. </Tabs>
  5138. <Note>
  5139. Make sure you pass in the absolute path to your server.
  5140. </Note>
  5141. This tells Claude for Desktop:
  5142. 1. There's an MCP server named "my-weather-server"
  5143. 2. To launch it by running `java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar`
  5144. Save the file, and restart **Claude for Desktop**.
  5145. ## Testing your server with Java client
  5146. ### Create a MCP Client manually
  5147. Use the `McpClient` to connect to the server:
  5148. ```java
  5149. var stdioParams = ServerParameters.builder("java")
  5150. .args("-jar", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar")
  5151. .build();
  5152. var stdioTransport = new StdioClientTransport(stdioParams);
  5153. var mcpClient = McpClient.sync(stdioTransport).build();
  5154. mcpClient.initialize();
  5155. ListToolsResult toolsList = mcpClient.listTools();
  5156. CallToolResult weather = mcpClient.callTool(
  5157. new CallToolRequest("getWeatherForecastByLocation",
  5158. Map.of("latitude", "47.6062", "longitude", "-122.3321")));
  5159. CallToolResult alert = mcpClient.callTool(
  5160. new CallToolRequest("getAlerts", Map.of("state", "NY")));
  5161. mcpClient.closeGracefully();
  5162. ```
  5163. ### Use MCP Client Boot Starter
  5164. Create a new boot starter application using the `spring-ai-starter-mcp-client` dependency:
  5165. ```xml
  5166. <dependency>
  5167. <groupId>org.springframework.ai</groupId>
  5168. <artifactId>spring-ai-starter-mcp-client</artifactId>
  5169. </dependency>
  5170. ```
  5171. and set the `spring.ai.mcp.client.stdio.servers-configuration` property to point to your `claude_desktop_config.json`.
  5172. You can re-use the existing Anthropic Desktop configuration:
  5173. ```properties
  5174. spring.ai.mcp.client.stdio.servers-configuration=file:PATH/TO/claude_desktop_config.json
  5175. ```
  5176. When you start your client application, the auto-configuration will create, automatically MCP clients from the claude\_desktop\_config.json.
  5177. For more information, see the [MCP Client Boot Starters](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-client-docs.html) reference documentation.
  5178. ## More Java MCP Server examples
  5179. The [starter-webflux-server](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-webflux-server) demonstrates how to create a MCP server using SSE transport.
  5180. It showcases how to define and register MCP Tools, Resources, and Prompts, using the Spring Boot's auto-configuration capabilities.
  5181. </Tab>
  5182. <Tab title="Kotlin">
  5183. Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/weather-stdio-server)
  5184. ### Prerequisite knowledge
  5185. This quickstart assumes you have familiarity with:
  5186. * Kotlin
  5187. * LLMs like Claude
  5188. ### System requirements
  5189. * Java 17 or higher installed.
  5190. ### Set up your environment
  5191. First, let's install `java` and `gradle` if you haven't already.
  5192. You can download `java` from [official Oracle JDK website](https://www.oracle.com/java/technologies/downloads/).
  5193. Verify your `java` installation:
  5194. ```bash
  5195. java --version
  5196. ```
  5197. Now, let's create and set up your project:
  5198. <CodeGroup>
  5199. ```bash MacOS/Linux
  5200. # Create a new directory for our project
  5201. mkdir weather
  5202. cd weather
  5203. # Initialize a new kotlin project
  5204. gradle init
  5205. ```
  5206. ```powershell Windows
  5207. # Create a new directory for our project
  5208. md weather
  5209. cd weather
  5210. # Initialize a new kotlin project
  5211. gradle init
  5212. ```
  5213. </CodeGroup>
  5214. After running `gradle init`, you will be presented with options for creating your project.
  5215. Select **Application** as the project type, **Kotlin** as the programming language, and **Java 17** as the Java version.
  5216. Alternatively, you can create a Kotlin application using the [IntelliJ IDEA project wizard](https://kotlinlang.org/docs/jvm-get-started.html).
  5217. After creating the project, add the following dependencies:
  5218. <CodeGroup>
  5219. ```kotlin build.gradle.kts
  5220. val mcpVersion = "0.4.0"
  5221. val slf4jVersion = "2.0.9"
  5222. val ktorVersion = "3.1.1"
  5223. dependencies {
  5224. implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion")
  5225. implementation("org.slf4j:slf4j-nop:$slf4jVersion")
  5226. implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion")
  5227. implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")
  5228. }
  5229. ```
  5230. ```groovy build.gradle
  5231. def mcpVersion = '0.3.0'
  5232. def slf4jVersion = '2.0.9'
  5233. def ktorVersion = '3.1.1'
  5234. dependencies {
  5235. implementation "io.modelcontextprotocol:kotlin-sdk:$mcpVersion"
  5236. implementation "org.slf4j:slf4j-nop:$slf4jVersion"
  5237. implementation "io.ktor:ktor-client-content-negotiation:$ktorVersion"
  5238. implementation "io.ktor:ktor-serialization-kotlinx-json:$ktorVersion"
  5239. }
  5240. ```
  5241. </CodeGroup>
  5242. Also, add the following plugins to your build script:
  5243. <CodeGroup>
  5244. ```kotlin build.gradle.kts
  5245. plugins {
  5246. kotlin("plugin.serialization") version "your_version_of_kotlin"
  5247. id("com.github.johnrengelman.shadow") version "8.1.1"
  5248. }
  5249. ```
  5250. ```groovy build.gradle
  5251. plugins {
  5252. id 'org.jetbrains.kotlin.plugin.serialization' version 'your_version_of_kotlin'
  5253. id 'com.github.johnrengelman.shadow' version '8.1.1'
  5254. }
  5255. ```
  5256. </CodeGroup>
  5257. Now let’s dive into building your server.
  5258. ## Building your server
  5259. ### Setting up the instance
  5260. Add a server initialization function:
  5261. ```kotlin
  5262. // Main function to run the MCP server
  5263. fun `run mcp server`() {
  5264. // Create the MCP Server instance with a basic implementation
  5265. val server = Server(
  5266. Implementation(
  5267. name = "weather", // Tool name is "weather"
  5268. version = "1.0.0" // Version of the implementation
  5269. ),
  5270. ServerOptions(
  5271. capabilities = ServerCapabilities(tools = ServerCapabilities.Tools(listChanged = true))
  5272. )
  5273. )
  5274. // Create a transport using standard IO for server communication
  5275. val transport = StdioServerTransport(
  5276. System.`in`.asInput(),
  5277. System.out.asSink().buffered()
  5278. )
  5279. runBlocking {
  5280. server.connect(transport)
  5281. val done = Job()
  5282. server.onClose {
  5283. done.complete()
  5284. }
  5285. done.join()
  5286. }
  5287. }
  5288. ```
  5289. ### Weather API helper functions
  5290. Next, let's add functions and data classes for querying and converting responses from the National Weather Service API:
  5291. ```kotlin
  5292. // Extension function to fetch forecast information for given latitude and longitude
  5293. suspend fun HttpClient.getForecast(latitude: Double, longitude: Double): List<String> {
  5294. val points = this.get("/points/$latitude,$longitude").body<Points>()
  5295. val forecast = this.get(points.properties.forecast).body<Forecast>()
  5296. return forecast.properties.periods.map { period ->
  5297. """
  5298. ${period.name}:
  5299. Temperature: ${period.temperature} ${period.temperatureUnit}
  5300. Wind: ${period.windSpeed} ${period.windDirection}
  5301. Forecast: ${period.detailedForecast}
  5302. """.trimIndent()
  5303. }
  5304. }
  5305. // Extension function to fetch weather alerts for a given state
  5306. suspend fun HttpClient.getAlerts(state: String): List<String> {
  5307. val alerts = this.get("/alerts/active/area/$state").body<Alert>()
  5308. return alerts.features.map { feature ->
  5309. """
  5310. Event: ${feature.properties.event}
  5311. Area: ${feature.properties.areaDesc}
  5312. Severity: ${feature.properties.severity}
  5313. Description: ${feature.properties.description}
  5314. Instruction: ${feature.properties.instruction}
  5315. """.trimIndent()
  5316. }
  5317. }
  5318. @Serializable
  5319. data class Points(
  5320. val properties: Properties
  5321. ) {
  5322. @Serializable
  5323. data class Properties(val forecast: String)
  5324. }
  5325. @Serializable
  5326. data class Forecast(
  5327. val properties: Properties
  5328. ) {
  5329. @Serializable
  5330. data class Properties(val periods: List<Period>)
  5331. @Serializable
  5332. data class Period(
  5333. val number: Int, val name: String, val startTime: String, val endTime: String,
  5334. val isDaytime: Boolean, val temperature: Int, val temperatureUnit: String,
  5335. val temperatureTrend: String, val probabilityOfPrecipitation: JsonObject,
  5336. val windSpeed: String, val windDirection: String,
  5337. val shortForecast: String, val detailedForecast: String,
  5338. )
  5339. }
  5340. @Serializable
  5341. data class Alert(
  5342. val features: List<Feature>
  5343. ) {
  5344. @Serializable
  5345. data class Feature(
  5346. val properties: Properties
  5347. )
  5348. @Serializable
  5349. data class Properties(
  5350. val event: String, val areaDesc: String, val severity: String,
  5351. val description: String, val instruction: String?,
  5352. )
  5353. }
  5354. ```
  5355. ### Implementing tool execution
  5356. The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
  5357. ```kotlin
  5358. // Create an HTTP client with a default request configuration and JSON content negotiation
  5359. val httpClient = HttpClient {
  5360. defaultRequest {
  5361. url("https://api.weather.gov")
  5362. headers {
  5363. append("Accept", "application/geo+json")
  5364. append("User-Agent", "WeatherApiClient/1.0")
  5365. }
  5366. contentType(ContentType.Application.Json)
  5367. }
  5368. // Install content negotiation plugin for JSON serialization/deserialization
  5369. install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) }
  5370. }
  5371. // Register a tool to fetch weather alerts by state
  5372. server.addTool(
  5373. name = "get_alerts",
  5374. description = """
  5375. Get weather alerts for a US state. Input is Two-letter US state code (e.g. CA, NY)
  5376. """.trimIndent(),
  5377. inputSchema = Tool.Input(
  5378. properties = buildJsonObject {
  5379. putJsonObject("state") {
  5380. put("type", "string")
  5381. put("description", "Two-letter US state code (e.g. CA, NY)")
  5382. }
  5383. },
  5384. required = listOf("state")
  5385. )
  5386. ) { request ->
  5387. val state = request.arguments["state"]?.jsonPrimitive?.content
  5388. if (state == null) {
  5389. return@addTool CallToolResult(
  5390. content = listOf(TextContent("The 'state' parameter is required."))
  5391. )
  5392. }
  5393. val alerts = httpClient.getAlerts(state)
  5394. CallToolResult(content = alerts.map { TextContent(it) })
  5395. }
  5396. // Register a tool to fetch weather forecast by latitude and longitude
  5397. server.addTool(
  5398. name = "get_forecast",
  5399. description = """
  5400. Get weather forecast for a specific latitude/longitude
  5401. """.trimIndent(),
  5402. inputSchema = Tool.Input(
  5403. properties = buildJsonObject {
  5404. putJsonObject("latitude") { put("type", "number") }
  5405. putJsonObject("longitude") { put("type", "number") }
  5406. },
  5407. required = listOf("latitude", "longitude")
  5408. )
  5409. ) { request ->
  5410. val latitude = request.arguments["latitude"]?.jsonPrimitive?.doubleOrNull
  5411. val longitude = request.arguments["longitude"]?.jsonPrimitive?.doubleOrNull
  5412. if (latitude == null || longitude == null) {
  5413. return@addTool CallToolResult(
  5414. content = listOf(TextContent("The 'latitude' and 'longitude' parameters are required."))
  5415. )
  5416. }
  5417. val forecast = httpClient.getForecast(latitude, longitude)
  5418. CallToolResult(content = forecast.map { TextContent(it) })
  5419. }
  5420. ```
  5421. ### Running the server
  5422. Finally, implement the main function to run the server:
  5423. ```kotlin
  5424. fun main() = `run mcp server`()
  5425. ```
  5426. Make sure to run `./gradlew build` to build your server. This is a very important step in getting your server to connect.
  5427. Let's now test your server from an existing MCP host, Claude for Desktop.
  5428. ## Testing your server with Claude for Desktop
  5429. <Note>
  5430. Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/quickstart/client) tutorial to build an MCP client that connects to the server we just built.
  5431. </Note>
  5432. First, make sure you have Claude for Desktop installed. [You can install the latest version
  5433. here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
  5434. We'll need to configure Claude for Desktop for whichever MCP servers you want to use.
  5435. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor.
  5436. Make sure to create the file if it doesn't exist.
  5437. For example, if you have [VS Code](https://code.visualstudio.com/) installed:
  5438. <CodeGroup>
  5439. ```bash MacOS/Linux
  5440. code ~/Library/Application\ Support/Claude/claude_desktop_config.json
  5441. ```
  5442. ```powershell Windows
  5443. code $env:AppData\Claude\claude_desktop_config.json
  5444. ```
  5445. </CodeGroup>
  5446. You'll then add your servers in the `mcpServers` key.
  5447. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
  5448. In this case, we'll add our single weather server like so:
  5449. <CodeGroup>
  5450. ```json MacOS/Linux
  5451. {
  5452. "mcpServers": {
  5453. "weather": {
  5454. "command": "java",
  5455. "args": [
  5456. "-jar",
  5457. "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/libs/weather-0.1.0-all.jar"
  5458. ]
  5459. }
  5460. }
  5461. }
  5462. ```
  5463. ```json Windows
  5464. {
  5465. "mcpServers": {
  5466. "weather": {
  5467. "command": "java",
  5468. "args": [
  5469. "-jar",
  5470. "C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\libs\\weather-0.1.0-all.jar"
  5471. ]
  5472. }
  5473. }
  5474. }
  5475. ```
  5476. </CodeGroup>
  5477. This tells Claude for Desktop:
  5478. 1. There's an MCP server named "weather"
  5479. 2. Launch it by running `java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/libs/weather-0.1.0-all.jar`
  5480. Save the file, and restart **Claude for Desktop**.
  5481. </Tab>
  5482. <Tab title="C#">
  5483. Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/csharp-sdk/tree/main/samples/QuickstartWeatherServer)
  5484. ### Prerequisite knowledge
  5485. This quickstart assumes you have familiarity with:
  5486. * C#
  5487. * LLMs like Claude
  5488. * .NET 8 or higher
  5489. ### System requirements
  5490. * [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) or higher installed.
  5491. ### Set up your environment
  5492. First, let's install `dotnet` if you haven't already. You can download `dotnet` from [official Microsoft .NET website](https://dotnet.microsoft.com/download/). Verify your `dotnet` installation:
  5493. ```bash
  5494. dotnet --version
  5495. ```
  5496. Now, let's create and set up your project:
  5497. <CodeGroup>
  5498. ```bash MacOS/Linux
  5499. # Create a new directory for our project
  5500. mkdir weather
  5501. cd weather
  5502. # Initialize a new C# project
  5503. dotnet new console
  5504. ```
  5505. ```powershell Windows
  5506. # Create a new directory for our project
  5507. mkdir weather
  5508. cd weather
  5509. # Initialize a new C# project
  5510. dotnet new console
  5511. ```
  5512. </CodeGroup>
  5513. After running `dotnet new console`, you will be presented with a new C# project.
  5514. You can open the project in your favorite IDE, such as [Visual Studio](https://visualstudio.microsoft.com/) or [Rider](https://www.jetbrains.com/rider/).
  5515. Alternatively, you can create a C# application using the [Visual Studio project wizard](https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-console?view=vs-2022).
  5516. After creating the project, add NuGet package for the Model Context Protocol SDK and hosting:
  5517. ```bash
  5518. # Add the Model Context Protocol SDK NuGet package
  5519. dotnet add package ModelContextProtocol --prerelease
  5520. # Add the .NET Hosting NuGet package
  5521. dotnet add package Microsoft.Extensions.Hosting
  5522. ```
  5523. Now let’s dive into building your server.
  5524. ## Building your server
  5525. Open the `Program.cs` file in your project and replace its contents with the following code:
  5526. ```csharp
  5527. using Microsoft.Extensions.DependencyInjection;
  5528. using Microsoft.Extensions.Hosting;
  5529. using ModelContextProtocol;
  5530. using System.Net.Http.Headers;
  5531. var builder = Host.CreateEmptyApplicationBuilder(settings: null);
  5532. builder.Services.AddMcpServer()
  5533. .WithStdioServerTransport()
  5534. .WithToolsFromAssembly();
  5535. builder.Services.AddSingleton(_ =>
  5536. {
  5537. var client = new HttpClient() { BaseAddress = new Uri("https://api.weather.gov") };
  5538. client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("weather-tool", "1.0"));
  5539. return client;
  5540. });
  5541. var app = builder.Build();
  5542. await app.RunAsync();
  5543. ```
  5544. <Note>
  5545. When creating the `ApplicationHostBuilder`, ensure you use `CreateEmptyApplicationBuilder` instead of `CreateDefaultBuilder`. This ensures that the server does not write any additional messages to the console. This is only neccessary for servers using STDIO transport.
  5546. </Note>
  5547. This code sets up a basic console application that uses the Model Context Protocol SDK to create an MCP server with standard I/O transport.
  5548. ### Weather API helper functions
  5549. Create an extension class for `HttpClient` which helps simplify JSON request handling:
  5550. ```csharp
  5551. using System.Text.Json;
  5552. internal static class HttpClientExt
  5553. {
  5554. public static async Task<JsonDocument> ReadJsonDocumentAsync(this HttpClient client, string requestUri)
  5555. {
  5556. using var response = await client.GetAsync(requestUri);
  5557. response.EnsureSuccessStatusCode();
  5558. return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
  5559. }
  5560. }
  5561. ```
  5562. Next, define a class with the tool execution handlers for querying and converting responses from the National Weather Service API:
  5563. ```csharp
  5564. using ModelContextProtocol.Server;
  5565. using System.ComponentModel;
  5566. using System.Globalization;
  5567. using System.Text.Json;
  5568. namespace QuickstartWeatherServer.Tools;
  5569. [McpServerToolType]
  5570. public static class WeatherTools
  5571. {
  5572. [McpServerTool, Description("Get weather alerts for a US state.")]
  5573. public static async Task<string> GetAlerts(
  5574. HttpClient client,
  5575. [Description("The US state to get alerts for.")] string state)
  5576. {
  5577. using var jsonDocument = await client.ReadJsonDocumentAsync($"/alerts/active/area/{state}");
  5578. var jsonElement = jsonDocument.RootElement;
  5579. var alerts = jsonElement.GetProperty("features").EnumerateArray();
  5580. if (!alerts.Any())
  5581. {
  5582. return "No active alerts for this state.";
  5583. }
  5584. return string.Join("\n--\n", alerts.Select(alert =>
  5585. {
  5586. JsonElement properties = alert.GetProperty("properties");
  5587. return $"""
  5588. Event: {properties.GetProperty("event").GetString()}
  5589. Area: {properties.GetProperty("areaDesc").GetString()}
  5590. Severity: {properties.GetProperty("severity").GetString()}
  5591. Description: {properties.GetProperty("description").GetString()}
  5592. Instruction: {properties.GetProperty("instruction").GetString()}
  5593. """;
  5594. }));
  5595. }
  5596. [McpServerTool, Description("Get weather forecast for a location.")]
  5597. public static async Task<string> GetForecast(
  5598. HttpClient client,
  5599. [Description("Latitude of the location.")] double latitude,
  5600. [Description("Longitude of the location.")] double longitude)
  5601. {
  5602. var pointUrl = string.Create(CultureInfo.InvariantCulture, $"/points/{latitude},{longitude}");
  5603. using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);
  5604. var forecastUrl = jsonDocument.RootElement.GetProperty("properties").GetProperty("forecast").GetString()
  5605. ?? throw new Exception($"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}");
  5606. using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl);
  5607. var periods = forecastDocument.RootElement.GetProperty("properties").GetProperty("periods").EnumerateArray();
  5608. return string.Join("\n---\n", periods.Select(period => $"""
  5609. {period.GetProperty("name").GetString()}
  5610. Temperature: {period.GetProperty("temperature").GetInt32()}°F
  5611. Wind: {period.GetProperty("windSpeed").GetString()} {period.GetProperty("windDirection").GetString()}
  5612. Forecast: {period.GetProperty("detailedForecast").GetString()}
  5613. """));
  5614. }
  5615. }
  5616. ```
  5617. ### Running the server
  5618. Finally, run the server using the following command:
  5619. ```bash
  5620. dotnet run
  5621. ```
  5622. This will start the server and listen for incoming requests on standard input/output.
  5623. ## Testing your server with Claude for Desktop
  5624. <Note>
  5625. Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/quickstart/client) tutorial to build an MCP client that connects to the server we just built.
  5626. </Note>
  5627. First, make sure you have Claude for Desktop installed. [You can install the latest version
  5628. here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.**
  5629. We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist.
  5630. For example, if you have [VS Code](https://code.visualstudio.com/) installed:
  5631. <Tabs>
  5632. <Tab title="MacOS/Linux">
  5633. ```bash
  5634. code ~/Library/Application\ Support/Claude/claude_desktop_config.json
  5635. ```
  5636. </Tab>
  5637. <Tab title="Windows">
  5638. ```powershell
  5639. code $env:AppData\Claude\claude_desktop_config.json
  5640. ```
  5641. </Tab>
  5642. </Tabs>
  5643. You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
  5644. In this case, we'll add our single weather server like so:
  5645. <Tabs>
  5646. <Tab title="MacOS/Linux">
  5647. ```json
  5648. {
  5649. "mcpServers": {
  5650. "weather": {
  5651. "command": "dotnet",
  5652. "args": ["run", "--project", "/ABSOLUTE/PATH/TO/PROJECT", "--no-build"]
  5653. }
  5654. }
  5655. }
  5656. ```
  5657. </Tab>
  5658. <Tab title="Windows">
  5659. ```json
  5660. {
  5661. "mcpServers": {
  5662. "weather": {
  5663. "command": "dotnet",
  5664. "args": [
  5665. "run",
  5666. "--project",
  5667. "C:\\ABSOLUTE\\PATH\\TO\\PROJECT",
  5668. "--no-build"
  5669. ]
  5670. }
  5671. }
  5672. }
  5673. ```
  5674. </Tab>
  5675. </Tabs>
  5676. This tells Claude for Desktop:
  5677. 1. There's an MCP server named "weather"
  5678. 2. Launch it by running `dotnet run /ABSOLUTE/PATH/TO/PROJECT`
  5679. Save the file, and restart **Claude for Desktop**.
  5680. </Tab>
  5681. </Tabs>
  5682. ### Test with commands
  5683. Let's make sure Claude for Desktop is picking up the two tools we've exposed in our `weather` server. You can do this by looking for the "Search and tools" <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-slider.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon:
  5684. <Frame>
  5685. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/visual-indicator-mcp-tools.png" />
  5686. </Frame>
  5687. After clicking on the slider icon, you should see two tools listed:
  5688. <Frame>
  5689. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/available-mcp-tools.png" />
  5690. </Frame>
  5691. If your server isn't being picked up by Claude for Desktop, proceed to the [Troubleshooting](#troubleshooting) section for debugging tips.
  5692. If the tool settings icon has shown up, you can now test your server by running the following commands in Claude for Desktop:
  5693. * What's the weather in Sacramento?
  5694. * What are the active weather alerts in Texas?
  5695. <Frame>
  5696. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/current-weather.png" />
  5697. </Frame>
  5698. <Frame>
  5699. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/weather-alerts.png" />
  5700. </Frame>
  5701. <Note>
  5702. Since this is the US National Weather service, the queries will only work for US locations.
  5703. </Note>
  5704. ## What's happening under the hood
  5705. When you ask a question:
  5706. 1. The client sends your question to Claude
  5707. 2. Claude analyzes the available tools and decides which one(s) to use
  5708. 3. The client executes the chosen tool(s) through the MCP server
  5709. 4. The results are sent back to Claude
  5710. 5. Claude formulates a natural language response
  5711. 6. The response is displayed to you!
  5712. ## Troubleshooting
  5713. <AccordionGroup>
  5714. <Accordion title="Claude for Desktop Integration Issues">
  5715. **Getting logs from Claude for Desktop**
  5716. Claude.app logging related to MCP is written to log files in `~/Library/Logs/Claude`:
  5717. * `mcp.log` will contain general logging about MCP connections and connection failures.
  5718. * Files named `mcp-server-SERVERNAME.log` will contain error (stderr) logging from the named server.
  5719. You can run the following command to list recent logs and follow along with any new ones:
  5720. ```bash
  5721. # Check Claude's logs for errors
  5722. tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
  5723. ```
  5724. **Server not showing up in Claude**
  5725. 1. Check your `claude_desktop_config.json` file syntax
  5726. 2. Make sure the path to your project is absolute and not relative
  5727. 3. Restart Claude for Desktop completely
  5728. **Tool calls failing silently**
  5729. If Claude attempts to use the tools but they fail:
  5730. 1. Check Claude's logs for errors
  5731. 2. Verify your server builds and runs without errors
  5732. 3. Try restarting Claude for Desktop
  5733. **None of this is working. What do I do?**
  5734. Please refer to our [debugging guide](/docs/tools/debugging) for better debugging tools and more detailed guidance.
  5735. </Accordion>
  5736. <Accordion title="Weather API Issues">
  5737. **Error: Failed to retrieve grid point data**
  5738. This usually means either:
  5739. 1. The coordinates are outside the US
  5740. 2. The NWS API is having issues
  5741. 3. You're being rate limited
  5742. Fix:
  5743. * Verify you're using US coordinates
  5744. * Add a small delay between requests
  5745. * Check the NWS API status page
  5746. **Error: No active alerts for \[STATE]**
  5747. This isn't an error - it just means there are no current weather alerts for that state. Try a different state or check during severe weather.
  5748. </Accordion>
  5749. </AccordionGroup>
  5750. <Note>
  5751. For more advanced troubleshooting, check out our guide on [Debugging MCP](/docs/tools/debugging)
  5752. </Note>
  5753. ## Next steps
  5754. <CardGroup cols={2}>
  5755. <Card title="Building a client" icon="outlet" href="/quickstart/client">
  5756. Learn how to build your own MCP client that can connect to your server
  5757. </Card>
  5758. <Card title="Example servers" icon="grid" href="/examples">
  5759. Check out our gallery of official MCP servers and implementations
  5760. </Card>
  5761. <Card title="Debugging Guide" icon="bug" href="/docs/tools/debugging">
  5762. Learn how to effectively debug MCP servers and integrations
  5763. </Card>
  5764. <Card title="Building MCP with LLMs" icon="comments" href="/tutorials/building-mcp-with-llms">
  5765. Learn how to use LLMs like Claude to speed up your MCP development
  5766. </Card>
  5767. </CardGroup>
  5768. # For Claude Desktop Users
  5769. Source: https://modelcontextprotocol.io/quickstart/user
  5770. Get started using pre-built servers in Claude for Desktop.
  5771. In this tutorial, you will extend [Claude for Desktop](https://claude.ai/download) so that it can read from your computer's file system, write new files, move files, and even search files.
  5772. <Frame>
  5773. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-filesystem.png" />
  5774. </Frame>
  5775. Don't worry — it will ask you for your permission before executing these actions!
  5776. ## 1. Download Claude for Desktop
  5777. Start by downloading [Claude for Desktop](https://claude.ai/download), choosing either macOS or Windows. (Linux is not yet supported for Claude for Desktop.)
  5778. Follow the installation instructions.
  5779. If you already have Claude for Desktop, make sure it's on the latest version by clicking on the Claude menu on your computer and selecting "Check for Updates..."
  5780. <Accordion title="Why Claude for Desktop and not Claude.ai?">
  5781. Because servers are locally run, MCP currently only supports desktop hosts. Remote hosts are in active development.
  5782. </Accordion>
  5783. ## 2. Add the Filesystem MCP Server
  5784. To add this filesystem functionality, we will be installing a pre-built [Filesystem MCP Server](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem) to Claude for Desktop. This is one of several current [reference servers](https://github.com/modelcontextprotocol/servers/tree/main) and many community-created servers.
  5785. Get started by opening up the Claude menu on your computer and select "Settings..." Please note that these are not the Claude Account Settings found in the app window itself.
  5786. This is what it should look like on a Mac:
  5787. <Frame style={{ textAlign: "center" }}>
  5788. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-menu.png" width="400" />
  5789. </Frame>
  5790. Click on "Developer" in the left-hand bar of the Settings pane, and then click on "Edit Config":
  5791. <Frame>
  5792. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-developer.png" />
  5793. </Frame>
  5794. This will create a configuration file at:
  5795. * macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
  5796. * Windows: `%APPDATA%\Claude\claude_desktop_config.json`
  5797. if you don't already have one, and will display the file in your file system.
  5798. Open up the configuration file in any text editor. Replace the file contents with this:
  5799. <Tabs>
  5800. <Tab title="MacOS/Linux">
  5801. ```json
  5802. {
  5803. "mcpServers": {
  5804. "filesystem": {
  5805. "command": "npx",
  5806. "args": [
  5807. "-y",
  5808. "@modelcontextprotocol/server-filesystem",
  5809. "/Users/username/Desktop",
  5810. "/Users/username/Downloads"
  5811. ]
  5812. }
  5813. }
  5814. }
  5815. ```
  5816. </Tab>
  5817. <Tab title="Windows">
  5818. ```json
  5819. {
  5820. "mcpServers": {
  5821. "filesystem": {
  5822. "command": "npx",
  5823. "args": [
  5824. "-y",
  5825. "@modelcontextprotocol/server-filesystem",
  5826. "C:\\Users\\username\\Desktop",
  5827. "C:\\Users\\username\\Downloads"
  5828. ]
  5829. }
  5830. }
  5831. }
  5832. ```
  5833. </Tab>
  5834. </Tabs>
  5835. Make sure to replace `username` with your computer's username. The paths should point to valid directories that you want Claude to be able to access and modify. It's set up to work for Desktop and Downloads, but you can add more paths as well.
  5836. You will also need [Node.js](https://nodejs.org) on your computer for this to run properly. To verify you have Node installed, open the command line on your computer.
  5837. * On macOS, open the Terminal from your Applications folder
  5838. * On Windows, press Windows + R, type "cmd", and press Enter
  5839. Once in the command line, verify you have Node installed by entering in the following command:
  5840. ```bash
  5841. node --version
  5842. ```
  5843. If you get an error saying "command not found" or "node is not recognized", download Node from [nodejs.org](https://nodejs.org/).
  5844. <Tip>
  5845. **How does the configuration file work?**
  5846. This configuration file tells Claude for Desktop which MCP servers to start up every time you start the application. In this case, we have added one server called "filesystem" that will use the Node `npx` command to install and run `@modelcontextprotocol/server-filesystem`. This server, described [here](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem), will let you access your file system in Claude for Desktop.
  5847. </Tip>
  5848. <Warning>
  5849. **Command Privileges**
  5850. Claude for Desktop will run the commands in the configuration file with the permissions of your user account, and access to your local files. Only add commands if you understand and trust the source.
  5851. </Warning>
  5852. ## 3. Restart Claude
  5853. After updating your configuration file, you need to restart Claude for Desktop.
  5854. Upon restarting, you should see a slider <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-slider.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon in the bottom left corner of the input box:
  5855. <Frame>
  5856. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-slider.png" />
  5857. </Frame>
  5858. After clicking on the slider icon, you should see the tools that come with the Filesystem MCP Server:
  5859. <Frame style={{ textAlign: "center" }}>
  5860. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-tools.png" width="400" />
  5861. </Frame>
  5862. If your server isn't being picked up by Claude for Desktop, proceed to the [Troubleshooting](#troubleshooting) section for debugging tips.
  5863. ## 4. Try it out!
  5864. You can now talk to Claude and ask it about your filesystem. It should know when to call the relevant tools.
  5865. Things you might try asking Claude:
  5866. * Can you write a poem and save it to my desktop?
  5867. * What are some work-related files in my downloads folder?
  5868. * Can you take all the images on my desktop and move them to a new folder called "Images"?
  5869. As needed, Claude will call the relevant tools and seek your approval before taking an action:
  5870. <Frame style={{ textAlign: "center" }}>
  5871. <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-approve.png" width="500" />
  5872. </Frame>
  5873. ## Troubleshooting
  5874. <AccordionGroup>
  5875. <Accordion title="Server not showing up in Claude / hammer icon missing">
  5876. 1. Restart Claude for Desktop completely
  5877. 2. Check your `claude_desktop_config.json` file syntax
  5878. 3. Make sure the file paths included in `claude_desktop_config.json` are valid and that they are absolute and not relative
  5879. 4. Look at [logs](#getting-logs-from-claude-for-desktop) to see why the server is not connecting
  5880. 5. In your command line, try manually running the server (replacing `username` as you did in `claude_desktop_config.json`) to see if you get any errors:
  5881. <Tabs>
  5882. <Tab title="MacOS/Linux">
  5883. ```bash
  5884. npx -y @modelcontextprotocol/server-filesystem /Users/username/Desktop /Users/username/Downloads
  5885. ```
  5886. </Tab>
  5887. <Tab title="Windows">
  5888. ```bash
  5889. npx -y @modelcontextprotocol/server-filesystem C:\Users\username\Desktop C:\Users\username\Downloads
  5890. ```
  5891. </Tab>
  5892. </Tabs>
  5893. </Accordion>
  5894. <Accordion title="Getting logs from Claude for Desktop">
  5895. Claude.app logging related to MCP is written to log files in:
  5896. * macOS: `~/Library/Logs/Claude`
  5897. * Windows: `%APPDATA%\Claude\logs`
  5898. * `mcp.log` will contain general logging about MCP connections and connection failures.
  5899. * Files named `mcp-server-SERVERNAME.log` will contain error (stderr) logging from the named server.
  5900. You can run the following command to list recent logs and follow along with any new ones (on Windows, it will only show recent logs):
  5901. <Tabs>
  5902. <Tab title="MacOS/Linux">
  5903. ```bash
  5904. # Check Claude's logs for errors
  5905. tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
  5906. ```
  5907. </Tab>
  5908. <Tab title="Windows">
  5909. ```bash
  5910. type "%APPDATA%\Claude\logs\mcp*.log"
  5911. ```
  5912. </Tab>
  5913. </Tabs>
  5914. </Accordion>
  5915. <Accordion title="Tool calls failing silently">
  5916. If Claude attempts to use the tools but they fail:
  5917. 1. Check Claude's logs for errors
  5918. 2. Verify your server builds and runs without errors
  5919. 3. Try restarting Claude for Desktop
  5920. </Accordion>
  5921. <Accordion title="None of this is working. What do I do?">
  5922. Please refer to our [debugging guide](/docs/tools/debugging) for better debugging tools and more detailed guidance.
  5923. </Accordion>
  5924. <Accordion title="ENOENT error and `${APPDATA}` in paths on Windows">
  5925. If your configured server fails to load, and you see within its logs an error referring to `${APPDATA}` within a path, you may need to add the expanded value of `%APPDATA%` to your `env` key in `claude_desktop_config.json`:
  5926. ```json
  5927. {
  5928. "brave-search": {
  5929. "command": "npx",
  5930. "args": ["-y", "@modelcontextprotocol/server-brave-search"],
  5931. "env": {
  5932. "APPDATA": "C:\\Users\\user\\AppData\\Roaming\\",
  5933. "BRAVE_API_KEY": "..."
  5934. }
  5935. }
  5936. }
  5937. ```
  5938. With this change in place, launch Claude Desktop once again.
  5939. <Warning>
  5940. **NPM should be installed globally**
  5941. The `npx` command may continue to fail if you have not installed NPM globally. If NPM is already installed globally, you will find `%APPDATA%\npm` exists on your system. If not, you can install NPM globally by running the following command:
  5942. ```bash
  5943. npm install -g npm
  5944. ```
  5945. </Warning>
  5946. </Accordion>
  5947. </AccordionGroup>
  5948. ## Next steps
  5949. <CardGroup cols={2}>
  5950. <Card title="Explore other servers" icon="grid" href="/examples">
  5951. Check out our gallery of official MCP servers and implementations
  5952. </Card>
  5953. <Card title="Build your own server" icon="code" href="/quickstart/server">
  5954. Now build your own custom server to use in Claude for Desktop and other
  5955. clients
  5956. </Card>
  5957. </CardGroup>
  5958. # MCP Client
  5959. Source: https://modelcontextprotocol.io/sdk/java/mcp-client
  5960. Learn how to use the Model Context Protocol (MCP) client to interact with MCP servers
  5961. # Model Context Protocol Client
  5962. The MCP Client is a key component in the Model Context Protocol (MCP) architecture, responsible for establishing and managing connections with MCP servers. It implements the client-side of the protocol, handling:
  5963. * Protocol version negotiation to ensure compatibility with servers
  5964. * Capability negotiation to determine available features
  5965. * Message transport and JSON-RPC communication
  5966. * Tool discovery and execution
  5967. * Resource access and management
  5968. * Prompt system interactions
  5969. * Optional features like roots management and sampling support
  5970. <Tip>
  5971. The core `io.modelcontextprotocol.sdk:mcp` module provides STDIO and SSE client transport implementations without requiring external web frameworks.
  5972. Spring-specific transport implementations are available as an **optional** dependency `io.modelcontextprotocol.sdk:mcp-spring-webflux` for [Spring Framework](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-client-boot-starter-docs.html) users.
  5973. </Tip>
  5974. The client provides both synchronous and asynchronous APIs for flexibility in different application contexts.
  5975. <Tabs>
  5976. <Tab title="Sync API">
  5977. ```java
  5978. // Create a sync client with custom configuration
  5979. McpSyncClient client = McpClient.sync(transport)
  5980. .requestTimeout(Duration.ofSeconds(10))
  5981. .capabilities(ClientCapabilities.builder()
  5982. .roots(true) // Enable roots capability
  5983. .sampling() // Enable sampling capability
  5984. .build())
  5985. .sampling(request -> new CreateMessageResult(response))
  5986. .build();
  5987. // Initialize connection
  5988. client.initialize();
  5989. // List available tools
  5990. ListToolsResult tools = client.listTools();
  5991. // Call a tool
  5992. CallToolResult result = client.callTool(
  5993. new CallToolRequest("calculator",
  5994. Map.of("operation", "add", "a", 2, "b", 3))
  5995. );
  5996. // List and read resources
  5997. ListResourcesResult resources = client.listResources();
  5998. ReadResourceResult resource = client.readResource(
  5999. new ReadResourceRequest("resource://uri")
  6000. );
  6001. // List and use prompts
  6002. ListPromptsResult prompts = client.listPrompts();
  6003. GetPromptResult prompt = client.getPrompt(
  6004. new GetPromptRequest("greeting", Map.of("name", "Spring"))
  6005. );
  6006. // Add/remove roots
  6007. client.addRoot(new Root("file:///path", "description"));
  6008. client.removeRoot("file:///path");
  6009. // Close client
  6010. client.closeGracefully();
  6011. ```
  6012. </Tab>
  6013. <Tab title="Async API">
  6014. ```java
  6015. // Create an async client with custom configuration
  6016. McpAsyncClient client = McpClient.async(transport)
  6017. .requestTimeout(Duration.ofSeconds(10))
  6018. .capabilities(ClientCapabilities.builder()
  6019. .roots(true) // Enable roots capability
  6020. .sampling() // Enable sampling capability
  6021. .build())
  6022. .sampling(request -> Mono.just(new CreateMessageResult(response)))
  6023. .toolsChangeConsumer(tools -> Mono.fromRunnable(() -> {
  6024. logger.info("Tools updated: {}", tools);
  6025. }))
  6026. .resourcesChangeConsumer(resources -> Mono.fromRunnable(() -> {
  6027. logger.info("Resources updated: {}", resources);
  6028. }))
  6029. .promptsChangeConsumer(prompts -> Mono.fromRunnable(() -> {
  6030. logger.info("Prompts updated: {}", prompts);
  6031. }))
  6032. .build();
  6033. // Initialize connection and use features
  6034. client.initialize()
  6035. .flatMap(initResult -> client.listTools())
  6036. .flatMap(tools -> {
  6037. return client.callTool(new CallToolRequest(
  6038. "calculator",
  6039. Map.of("operation", "add", "a", 2, "b", 3)
  6040. ));
  6041. })
  6042. .flatMap(result -> {
  6043. return client.listResources()
  6044. .flatMap(resources ->
  6045. client.readResource(new ReadResourceRequest("resource://uri"))
  6046. );
  6047. })
  6048. .flatMap(resource -> {
  6049. return client.listPrompts()
  6050. .flatMap(prompts ->
  6051. client.getPrompt(new GetPromptRequest(
  6052. "greeting",
  6053. Map.of("name", "Spring")
  6054. ))
  6055. );
  6056. })
  6057. .flatMap(prompt -> {
  6058. return client.addRoot(new Root("file:///path", "description"))
  6059. .then(client.removeRoot("file:///path"));
  6060. })
  6061. .doFinally(signalType -> {
  6062. client.closeGracefully().subscribe();
  6063. })
  6064. .subscribe();
  6065. ```
  6066. </Tab>
  6067. </Tabs>
  6068. ## Client Transport
  6069. The transport layer handles the communication between MCP clients and servers, providing different implementations for various use cases. The client transport manages message serialization, connection establishment, and protocol-specific communication patterns.
  6070. <Tabs>
  6071. <Tab title="STDIO">
  6072. Creates transport for in-process based communication
  6073. ```java
  6074. ServerParameters params = ServerParameters.builder("npx")
  6075. .args("-y", "@modelcontextprotocol/server-everything", "dir")
  6076. .build();
  6077. McpTransport transport = new StdioClientTransport(params);
  6078. ```
  6079. </Tab>
  6080. <Tab title="SSE (HttpClient)">
  6081. Creates a framework agnostic (pure Java API) SSE client transport. Included in the core mcp module.
  6082. ```java
  6083. McpTransport transport = new HttpClientSseClientTransport("http://your-mcp-server");
  6084. ```
  6085. </Tab>
  6086. <Tab title="SSE (WebFlux)">
  6087. Creates WebFlux-based SSE client transport. Requires the mcp-webflux-sse-transport dependency.
  6088. ```java
  6089. WebClient.Builder webClientBuilder = WebClient.builder()
  6090. .baseUrl("http://your-mcp-server");
  6091. McpTransport transport = new WebFluxSseClientTransport(webClientBuilder);
  6092. ```
  6093. </Tab>
  6094. </Tabs>
  6095. ## Client Capabilities
  6096. The client can be configured with various capabilities:
  6097. ```java
  6098. var capabilities = ClientCapabilities.builder()
  6099. .roots(true) // Enable filesystem roots support with list changes notifications
  6100. .sampling() // Enable LLM sampling support
  6101. .build();
  6102. ```
  6103. ### Roots Support
  6104. Roots define the boundaries of where servers can operate within the filesystem:
  6105. ```java
  6106. // Add a root dynamically
  6107. client.addRoot(new Root("file:///path", "description"));
  6108. // Remove a root
  6109. client.removeRoot("file:///path");
  6110. // Notify server of roots changes
  6111. client.rootsListChangedNotification();
  6112. ```
  6113. The roots capability allows servers to:
  6114. * Request the list of accessible filesystem roots
  6115. * Receive notifications when the roots list changes
  6116. * Understand which directories and files they have access to
  6117. ### Sampling Support
  6118. Sampling enables servers to request LLM interactions ("completions" or "generations") through the client:
  6119. ```java
  6120. // Configure sampling handler
  6121. Function<CreateMessageRequest, CreateMessageResult> samplingHandler = request -> {
  6122. // Sampling implementation that interfaces with LLM
  6123. return new CreateMessageResult(response);
  6124. };
  6125. // Create client with sampling support
  6126. var client = McpClient.sync(transport)
  6127. .capabilities(ClientCapabilities.builder()
  6128. .sampling()
  6129. .build())
  6130. .sampling(samplingHandler)
  6131. .build();
  6132. ```
  6133. This capability allows:
  6134. * Servers to leverage AI capabilities without requiring API keys
  6135. * Clients to maintain control over model access and permissions
  6136. * Support for both text and image-based interactions
  6137. * Optional inclusion of MCP server context in prompts
  6138. ### Logging Support
  6139. The client can register a logging consumer to receive log messages from the server and set the minimum logging level to filter messages:
  6140. ```java
  6141. var mcpClient = McpClient.sync(transport)
  6142. .loggingConsumer(notification -> {
  6143. System.out.println("Received log message: " + notification.data());
  6144. })
  6145. .build();
  6146. mcpClient.initialize();
  6147. mcpClient.setLoggingLevel(McpSchema.LoggingLevel.INFO);
  6148. // Call the tool that can sends logging notifications
  6149. CallToolResult result = mcpClient.callTool(new McpSchema.CallToolRequest("logging-test", Map.of()));
  6150. ```
  6151. Clients can control the minimum logging level they receive through the `mcpClient.setLoggingLevel(level)` request. Messages below the set level will be filtered out.
  6152. Supported logging levels (in order of increasing severity): DEBUG (0), INFO (1), NOTICE (2), WARNING (3), ERROR (4), CRITICAL (5), ALERT (6), EMERGENCY (7)
  6153. ## Using MCP Clients
  6154. ### Tool Execution
  6155. Tools are server-side functions that clients can discover and execute. The MCP client provides methods to list available tools and execute them with specific parameters. Each tool has a unique name and accepts a map of parameters.
  6156. <Tabs>
  6157. <Tab title="Sync API">
  6158. ```java
  6159. // List available tools and their names
  6160. var tools = client.listTools();
  6161. tools.forEach(tool -> System.out.println(tool.getName()));
  6162. // Execute a tool with parameters
  6163. var result = client.callTool("calculator", Map.of(
  6164. "operation", "add",
  6165. "a", 1,
  6166. "b", 2
  6167. ));
  6168. ```
  6169. </Tab>
  6170. <Tab title="Async API">
  6171. ```java
  6172. // List available tools asynchronously
  6173. client.listTools()
  6174. .doOnNext(tools -> tools.forEach(tool ->
  6175. System.out.println(tool.getName())))
  6176. .subscribe();
  6177. // Execute a tool asynchronously
  6178. client.callTool("calculator", Map.of(
  6179. "operation", "add",
  6180. "a", 1,
  6181. "b", 2
  6182. ))
  6183. .subscribe();
  6184. ```
  6185. </Tab>
  6186. </Tabs>
  6187. ### Resource Access
  6188. Resources represent server-side data sources that clients can access using URI templates. The MCP client provides methods to discover available resources and retrieve their contents through a standardized interface.
  6189. <Tabs>
  6190. <Tab title="Sync API">
  6191. ```java
  6192. // List available resources and their names
  6193. var resources = client.listResources();
  6194. resources.forEach(resource -> System.out.println(resource.getName()));
  6195. // Retrieve resource content using a URI template
  6196. var content = client.getResource("file", Map.of(
  6197. "path", "/path/to/file.txt"
  6198. ));
  6199. ```
  6200. </Tab>
  6201. <Tab title="Async API">
  6202. ```java
  6203. // List available resources asynchronously
  6204. client.listResources()
  6205. .doOnNext(resources -> resources.forEach(resource ->
  6206. System.out.println(resource.getName())))
  6207. .subscribe();
  6208. // Retrieve resource content asynchronously
  6209. client.getResource("file", Map.of(
  6210. "path", "/path/to/file.txt"
  6211. ))
  6212. .subscribe();
  6213. ```
  6214. </Tab>
  6215. </Tabs>
  6216. ### Prompt System
  6217. The prompt system enables interaction with server-side prompt templates. These templates can be discovered and executed with custom parameters, allowing for dynamic text generation based on predefined patterns.
  6218. <Tabs>
  6219. <Tab title="Sync API">
  6220. ```java
  6221. // List available prompt templates
  6222. var prompts = client.listPrompts();
  6223. prompts.forEach(prompt -> System.out.println(prompt.getName()));
  6224. // Execute a prompt template with parameters
  6225. var response = client.executePrompt("echo", Map.of(
  6226. "text", "Hello, World!"
  6227. ));
  6228. ```
  6229. </Tab>
  6230. <Tab title="Async API">
  6231. ```java
  6232. // List available prompt templates asynchronously
  6233. client.listPrompts()
  6234. .doOnNext(prompts -> prompts.forEach(prompt ->
  6235. System.out.println(prompt.getName())))
  6236. .subscribe();
  6237. // Execute a prompt template asynchronously
  6238. client.executePrompt("echo", Map.of(
  6239. "text", "Hello, World!"
  6240. ))
  6241. .subscribe();
  6242. ```
  6243. </Tab>
  6244. </Tabs>
  6245. ### Using Completion
  6246. As part of the [Completion capabilities](/specification/2025-03-26/server/utilities/completion), MCP provides a standardized way for servers to offer argument autocompletion suggestions for prompts and resource URIs.
  6247. Check the [Server Completion capabilities](/sdk/java/mcp-server#completion-specification) to learn how to enable and configure completions on the server side.
  6248. On the client side, the MCP client provides methods to request auto-completions:
  6249. <Tabs>
  6250. <Tab title="Sync API">
  6251. ```java
  6252. CompleteRequest request = new CompleteRequest(
  6253. new PromptReference("code_review"),
  6254. new CompleteRequest.CompleteArgument("language", "py"));
  6255. CompleteResult result = syncMcpClient.completeCompletion(request);
  6256. ```
  6257. </Tab>
  6258. <Tab title="Async API">
  6259. ```java
  6260. CompleteRequest request = new CompleteRequest(
  6261. new PromptReference("code_review"),
  6262. new CompleteRequest.CompleteArgument("language", "py"));
  6263. Mono<CompleteResult> result = mcpClient.completeCompletion(request);
  6264. ```
  6265. </Tab>
  6266. </Tabs>
  6267. # Overview
  6268. Source: https://modelcontextprotocol.io/sdk/java/mcp-overview
  6269. Introduction to the Model Context Protocol (MCP) Java SDK
  6270. Java SDK for the [Model Context Protocol](https://modelcontextprotocol.org/docs/concepts/architecture)
  6271. enables standardized integration between AI models and tools.
  6272. <Note>
  6273. ### Breaking Changes in 0.8.x ⚠️
  6274. **Note:** Version 0.8.x introduces several breaking changes including a new session-based architecture.
  6275. If you're upgrading from 0.7.0, please refer to the [Migration Guide](https://github.com/modelcontextprotocol/java-sdk/blob/main/migration-0.8.0.md) for detailed instructions.
  6276. </Note>
  6277. ## Features
  6278. * MCP Client and MCP Server implementations supporting:
  6279. * Protocol [version compatibility negotiation](/specification/2024-11-05/basic/lifecycle/#initialization)
  6280. * [Tool](/specification/2024-11-05/server/tools/) discovery, execution, list change notifications
  6281. * [Resource](/specification/2024-11-05/server/resources/) management with URI templates
  6282. * [Roots](/specification/2024-11-05/client/roots/) list management and notifications
  6283. * [Prompt](/specification/2024-11-05/server/prompts/) handling and management
  6284. * [Sampling](/specification/2024-11-05/client/sampling/) support for AI model interactions
  6285. * Multiple transport implementations:
  6286. * Default transports (included in core `mcp` module, no external web frameworks required):
  6287. * Stdio-based transport for process-based communication
  6288. * Java HttpClient-based SSE client transport for HTTP SSE Client-side streaming
  6289. * Servlet-based SSE server transport for HTTP SSE Server streaming
  6290. * Optional Spring-based transports (convenience if using Spring Framework):
  6291. * WebFlux SSE client and server transports for reactive HTTP streaming
  6292. * WebMVC SSE transport for servlet-based HTTP streaming
  6293. * Supports Synchronous and Asynchronous programming paradigms
  6294. <Tip>
  6295. The core `io.modelcontextprotocol.sdk:mcp` module provides default STDIO and SSE client and server transport implementations without requiring external web frameworks.
  6296. Spring-specific transports are available as optional dependencies for convenience when using the [Spring Framework](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-client-boot-starter-docs.html).
  6297. </Tip>
  6298. ## Architecture
  6299. The SDK follows a layered architecture with clear separation of concerns:
  6300. ![MCP Stack Architecture](https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/java/mcp-stack.svg)
  6301. * **Client/Server Layer (McpClient/McpServer)**: Both use McpSession for sync/async operations,
  6302. with McpClient handling client-side protocol operations and McpServer managing server-side protocol operations.
  6303. * **Session Layer (McpSession)**: Manages communication patterns and state using DefaultMcpSession implementation.
  6304. * **Transport Layer (McpTransport)**: Handles JSON-RPC message serialization/deserialization via:
  6305. * StdioTransport (stdin/stdout) in the core module
  6306. * HTTP SSE transports in dedicated transport modules (Java HttpClient, Spring WebFlux, Spring WebMVC)
  6307. The MCP Client is a key component in the Model Context Protocol (MCP) architecture, responsible for establishing and managing connections with MCP servers.
  6308. It implements the client-side of the protocol.
  6309. ![Java MCP Client Architecture](https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/java/java-mcp-client-architecture.jpg)
  6310. The MCP Server is a foundational component in the Model Context Protocol (MCP) architecture that provides tools, resources, and capabilities to clients.
  6311. It implements the server-side of the protocol.
  6312. ![Java MCP Server Architecture](https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/java/java-mcp-server-architecture.jpg)
  6313. Key Interactions:
  6314. * **Client/Server Initialization**: Transport setup, protocol compatibility check, capability negotiation, and implementation details exchange.
  6315. * **Message Flow**: JSON-RPC message handling with validation, type-safe response processing, and error handling.
  6316. * **Resource Management**: Resource discovery, URI template-based access, subscription system, and content retrieval.
  6317. ## Dependencies
  6318. Add the following Maven dependency to your project:
  6319. <Tabs>
  6320. <Tab title="Maven">
  6321. The core MCP functionality:
  6322. ```xml
  6323. <dependency>
  6324. <groupId>io.modelcontextprotocol.sdk</groupId>
  6325. <artifactId>mcp</artifactId>
  6326. </dependency>
  6327. ```
  6328. The core `mcp` module already includes default STDIO and SSE transport implementations and doesn't require external web frameworks.
  6329. If you're using the Spring Framework and want to use Spring-specific transport implementations, add one of the following optional dependencies:
  6330. ```xml
  6331. <!-- Optional: Spring WebFlux-based SSE client and server transport -->
  6332. <dependency>
  6333. <groupId>io.modelcontextprotocol.sdk</groupId>
  6334. <artifactId>mcp-spring-webflux</artifactId>
  6335. </dependency>
  6336. <!-- Optional: Spring WebMVC-based SSE server transport -->
  6337. <dependency>
  6338. <groupId>io.modelcontextprotocol.sdk</groupId>
  6339. <artifactId>mcp-spring-webmvc</artifactId>
  6340. </dependency>
  6341. ```
  6342. </Tab>
  6343. <Tab title="Gradle">
  6344. The core MCP functionality:
  6345. ```groovy
  6346. dependencies {
  6347. implementation platform("io.modelcontextprotocol.sdk:mcp")
  6348. //...
  6349. }
  6350. ```
  6351. The core `mcp` module already includes default STDIO and SSE transport implementations and doesn't require external web frameworks.
  6352. If you're using the Spring Framework and want to use Spring-specific transport implementations, add one of the following optional dependencies:
  6353. ```groovy
  6354. // Optional: Spring WebFlux-based SSE client and server transport
  6355. dependencies {
  6356. implementation platform("io.modelcontextprotocol.sdk:mcp-spring-webflux")
  6357. }
  6358. // Optional: Spring WebMVC-based SSE server transport
  6359. dependencies {
  6360. implementation platform("io.modelcontextprotocol.sdk:mcp-spring-webmvc")
  6361. }
  6362. ```
  6363. </Tab>
  6364. </Tabs>
  6365. ### Bill of Materials (BOM)
  6366. The Bill of Materials (BOM) declares the recommended versions of all the dependencies used by a given release.
  6367. Using the BOM from your application's build script avoids the need for you to specify and maintain the dependency versions yourself.
  6368. Instead, the version of the BOM you're using determines the utilized dependency versions.
  6369. It also ensures that you're using supported and tested versions of the dependencies by default, unless you choose to override them.
  6370. Add the BOM to your project:
  6371. <Tabs>
  6372. <Tab title="Maven">
  6373. ```xml
  6374. <dependencyManagement>
  6375. <dependencies>
  6376. <dependency>
  6377. <groupId>io.modelcontextprotocol.sdk</groupId>
  6378. <artifactId>mcp-bom</artifactId>
  6379. <version>0.9.0</version>
  6380. <type>pom</type>
  6381. <scope>import</scope>
  6382. </dependency>
  6383. </dependencies>
  6384. </dependencyManagement>
  6385. ```
  6386. </Tab>
  6387. <Tab title="Gradle">
  6388. ```groovy
  6389. dependencies {
  6390. implementation platform("io.modelcontextprotocol.sdk:mcp-bom:0.9.0")
  6391. //...
  6392. }
  6393. ```
  6394. Gradle users can also use the Spring AI MCP BOM by leveraging Gradle (5.0+) native support for declaring dependency constraints using a Maven BOM.
  6395. This is implemented by adding a 'platform' dependency handler method to the dependencies section of your Gradle build script.
  6396. As shown in the snippet above this can then be followed by version-less declarations of the Starter Dependencies for the one or more spring-ai modules you wish to use, e.g. spring-ai-openai.
  6397. </Tab>
  6398. </Tabs>
  6399. Replace the version number with the version of the BOM you want to use.
  6400. ### Available Dependencies
  6401. The following dependencies are available and managed by the BOM:
  6402. * Core Dependencies
  6403. * `io.modelcontextprotocol.sdk:mcp` - Core MCP library providing the base functionality and APIs for Model Context Protocol implementation, including default STDIO and SSE client and server transport implementations. No external web frameworks required.
  6404. * Optional Transport Dependencies (convenience if using Spring Framework)
  6405. * `io.modelcontextprotocol.sdk:mcp-spring-webflux` - WebFlux-based Server-Sent Events (SSE) transport implementation for reactive applications.
  6406. * `io.modelcontextprotocol.sdk:mcp-spring-webmvc` - WebMVC-based Server-Sent Events (SSE) transport implementation for servlet-based applications.
  6407. * Testing Dependencies
  6408. * `io.modelcontextprotocol.sdk:mcp-test` - Testing utilities and support for MCP-based applications.
  6409. # MCP Server
  6410. Source: https://modelcontextprotocol.io/sdk/java/mcp-server
  6411. Learn how to implement and configure a Model Context Protocol (MCP) server
  6412. <Note>
  6413. ### Breaking Changes in 0.8.x ⚠️
  6414. **Note:** Version 0.8.x introduces several breaking changes including a new session-based architecture.
  6415. If you're upgrading from 0.7.0, please refer to the [Migration Guide](https://github.com/modelcontextprotocol/java-sdk/blob/main/migration-0.8.0.md) for detailed instructions.
  6416. </Note>
  6417. ## Overview
  6418. The MCP Server is a foundational component in the Model Context Protocol (MCP) architecture that provides tools, resources, and capabilities to clients. It implements the server-side of the protocol, responsible for:
  6419. * Exposing tools that clients can discover and execute
  6420. * Managing resources with URI-based access patterns
  6421. * Providing prompt templates and handling prompt requests
  6422. * Supporting capability negotiation with clients
  6423. * Implementing server-side protocol operations
  6424. * Managing concurrent client connections
  6425. * Providing structured logging and notifications
  6426. <Tip>
  6427. The core `io.modelcontextprotocol.sdk:mcp` module provides STDIO and SSE server transport implementations without requiring external web frameworks.
  6428. Spring-specific transport implementations are available as an **optional** dependencies `io.modelcontextprotocol.sdk:mcp-spring-webflux`, `io.modelcontextprotocol.sdk:mcp-spring-webmvc` for [Spring Framework](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-client-boot-starter-docs.html) users.
  6429. </Tip>
  6430. The server supports both synchronous and asynchronous APIs, allowing for flexible integration in different application contexts.
  6431. <Tabs>
  6432. <Tab title="Sync API">
  6433. ```java
  6434. // Create a server with custom configuration
  6435. McpSyncServer syncServer = McpServer.sync(transportProvider)
  6436. .serverInfo("my-server", "1.0.0")
  6437. .capabilities(ServerCapabilities.builder()
  6438. .resources(false, true) // Enable resource support
  6439. .tools(true) // Enable tool support
  6440. .prompts(true) // Enable prompt support
  6441. .logging() // Enable logging support
  6442. .completions() // Enable completions support
  6443. .build())
  6444. .build();
  6445. // Register tools, resources, and prompts
  6446. syncServer.addTool(syncToolSpecification);
  6447. syncServer.addResource(syncResourceSpecification);
  6448. syncServer.addPrompt(syncPromptSpecification);
  6449. // Close the server when done
  6450. syncServer.close();
  6451. ```
  6452. </Tab>
  6453. <Tab title="Async API">
  6454. ```java
  6455. // Create an async server with custom configuration
  6456. McpAsyncServer asyncServer = McpServer.async(transportProvider)
  6457. .serverInfo("my-server", "1.0.0")
  6458. .capabilities(ServerCapabilities.builder()
  6459. .resources(false, true) // Enable resource support
  6460. .tools(true) // Enable tool support
  6461. .prompts(true) // Enable prompt support
  6462. .logging() // Enable logging support
  6463. .completions() // Enable completions support
  6464. .build())
  6465. .build();
  6466. // Register tools, resources, and prompts
  6467. asyncServer.addTool(asyncToolSpecification)
  6468. .doOnSuccess(v -> logger.info("Tool registered"))
  6469. .subscribe();
  6470. asyncServer.addResource(asyncResourceSpecification)
  6471. .doOnSuccess(v -> logger.info("Resource registered"))
  6472. .subscribe();
  6473. asyncServer.addPrompt(asyncPromptSpecification)
  6474. .doOnSuccess(v -> logger.info("Prompt registered"))
  6475. .subscribe();
  6476. // Close the server when done
  6477. asyncServer.close()
  6478. .doOnSuccess(v -> logger.info("Server closed"))
  6479. .subscribe();
  6480. ```
  6481. </Tab>
  6482. </Tabs>
  6483. ## Server Transport Providers
  6484. The transport layer in the MCP SDK is responsible for handling the communication between clients and servers.
  6485. It provides different implementations to support various communication protocols and patterns.
  6486. The SDK includes several built-in transport provider implementations:
  6487. <Tabs>
  6488. <Tab title="STDIO">
  6489. <>
  6490. Create in-process based transport:
  6491. ```java
  6492. StdioServerTransportProvider transportProvider = new StdioServerTransportProvider(new ObjectMapper());
  6493. ```
  6494. Provides bidirectional JSON-RPC message handling over standard input/output streams with non-blocking message processing, serialization/deserialization, and graceful shutdown support.
  6495. Key features:
  6496. <ul>
  6497. <li>Bidirectional communication through stdin/stdout</li>
  6498. <li>Process-based integration support</li>
  6499. <li>Simple setup and configuration</li>
  6500. <li>Lightweight implementation</li>
  6501. </ul>
  6502. </>
  6503. </Tab>
  6504. <Tab title="SSE (WebFlux)">
  6505. <>
  6506. <p>Creates WebFlux-based SSE server transport.<br />Requires the <code>mcp-spring-webflux</code> dependency.</p>
  6507. ```java
  6508. @Configuration
  6509. class McpConfig {
  6510. @Bean
  6511. WebFluxSseServerTransportProvider webFluxSseServerTransportProvider(ObjectMapper mapper) {
  6512. return new WebFluxSseServerTransportProvider(mapper, "/mcp/message");
  6513. }
  6514. @Bean
  6515. RouterFunction<?> mcpRouterFunction(WebFluxSseServerTransportProvider transportProvider) {
  6516. return transportProvider.getRouterFunction();
  6517. }
  6518. }
  6519. ```
  6520. <p>Implements the MCP HTTP with SSE transport specification, providing:</p>
  6521. <ul>
  6522. <li>Reactive HTTP streaming with WebFlux</li>
  6523. <li>Concurrent client connections through SSE endpoints</li>
  6524. <li>Message routing and session management</li>
  6525. <li>Graceful shutdown capabilities</li>
  6526. </ul>
  6527. </>
  6528. </Tab>
  6529. <Tab title="SSE (WebMvc)">
  6530. <>
  6531. <p>Creates WebMvc-based SSE server transport.<br />Requires the <code>mcp-spring-webmvc</code> dependency.</p>
  6532. ```java
  6533. @Configuration
  6534. @EnableWebMvc
  6535. class McpConfig {
  6536. @Bean
  6537. WebMvcSseServerTransportProvider webMvcSseServerTransportProvider(ObjectMapper mapper) {
  6538. return new WebMvcSseServerTransportProvider(mapper, "/mcp/message");
  6539. }
  6540. @Bean
  6541. RouterFunction<ServerResponse> mcpRouterFunction(WebMvcSseServerTransportProvider transportProvider) {
  6542. return transportProvider.getRouterFunction();
  6543. }
  6544. }
  6545. ```
  6546. <p>Implements the MCP HTTP with SSE transport specification, providing:</p>
  6547. <ul>
  6548. <li>Server-side event streaming</li>
  6549. <li>Integration with Spring WebMVC</li>
  6550. <li>Support for traditional web applications</li>
  6551. <li>Synchronous operation handling</li>
  6552. </ul>
  6553. </>
  6554. </Tab>
  6555. <Tab title="SSE (Servlet)">
  6556. <>
  6557. <p>
  6558. Creates a Servlet-based SSE server transport. It is included in the core <code>mcp</code> module.<br />
  6559. The <code>HttpServletSseServerTransport</code> can be used with any Servlet container.<br />
  6560. To use it with a Spring Web application, you can register it as a Servlet bean:
  6561. </p>
  6562. ```java
  6563. @Configuration
  6564. @EnableWebMvc
  6565. public class McpServerConfig implements WebMvcConfigurer {
  6566. @Bean
  6567. public HttpServletSseServerTransportProvider servletSseServerTransportProvider() {
  6568. return new HttpServletSseServerTransportProvider(new ObjectMapper(), "/mcp/message");
  6569. }
  6570. @Bean
  6571. public ServletRegistrationBean customServletBean(HttpServletSseServerTransportProvider transportProvider) {
  6572. return new ServletRegistrationBean(transportProvider);
  6573. }
  6574. }
  6575. ```
  6576. <p>
  6577. Implements the MCP HTTP with SSE transport specification using the traditional Servlet API, providing:
  6578. </p>
  6579. <ul>
  6580. <li>Asynchronous message handling using Servlet 6.0 async support</li>
  6581. <li>Session management for multiple client connections</li>
  6582. <li>
  6583. Two types of endpoints:
  6584. <ul>
  6585. <li>SSE endpoint (<code>/sse</code>) for server-to-client events</li>
  6586. <li>Message endpoint (configurable) for client-to-server requests</li>
  6587. </ul>
  6588. </li>
  6589. <li>Error handling and response formatting</li>
  6590. <li>Graceful shutdown support</li>
  6591. </ul>
  6592. </>
  6593. </Tab>
  6594. </Tabs>
  6595. ## Server Capabilities
  6596. The server can be configured with various capabilities:
  6597. ```java
  6598. var capabilities = ServerCapabilities.builder()
  6599. .resources(false, true) // Resource support with list changes notifications
  6600. .tools(true) // Tool support with list changes notifications
  6601. .prompts(true) // Prompt support with list changes notifications
  6602. .logging() // Enable logging support (enabled by default with logging level INFO)
  6603. .build();
  6604. ```
  6605. ### Logging Support
  6606. The server provides structured logging capabilities that allow sending log messages to clients with different severity levels:
  6607. ```java
  6608. // Send a log message to clients
  6609. server.loggingNotification(LoggingMessageNotification.builder()
  6610. .level(LoggingLevel.INFO)
  6611. .logger("custom-logger")
  6612. .data("Custom log message")
  6613. .build());
  6614. ```
  6615. Clients can control the minimum logging level they receive through the `mcpClient.setLoggingLevel(level)` request. Messages below the set level will be filtered out.
  6616. Supported logging levels (in order of increasing severity): DEBUG (0), INFO (1), NOTICE (2), WARNING (3), ERROR (4), CRITICAL (5), ALERT (6), EMERGENCY (7)
  6617. ### Tool Specification
  6618. The Model Context Protocol allows servers to [expose tools](/specification/2024-11-05/server/tools/) that can be invoked by language models.
  6619. The Java SDK allows implementing a Tool Specifications with their handler functions.
  6620. Tools enable AI models to perform calculations, access external APIs, query databases, and manipulate files:
  6621. <Tabs>
  6622. <Tab title="Sync">
  6623. ```java
  6624. // Sync tool specification
  6625. var schema = """
  6626. {
  6627. "type" : "object",
  6628. "id" : "urn:jsonschema:Operation",
  6629. "properties" : {
  6630. "operation" : {
  6631. "type" : "string"
  6632. },
  6633. "a" : {
  6634. "type" : "number"
  6635. },
  6636. "b" : {
  6637. "type" : "number"
  6638. }
  6639. }
  6640. }
  6641. """;
  6642. var syncToolSpecification = new McpServerFeatures.SyncToolSpecification(
  6643. new Tool("calculator", "Basic calculator", schema),
  6644. (exchange, arguments) -> {
  6645. // Tool implementation
  6646. return new CallToolResult(result, false);
  6647. }
  6648. );
  6649. ```
  6650. </Tab>
  6651. <Tab title="Async">
  6652. ```java
  6653. // Async tool specification
  6654. var schema = """
  6655. {
  6656. "type" : "object",
  6657. "id" : "urn:jsonschema:Operation",
  6658. "properties" : {
  6659. "operation" : {
  6660. "type" : "string"
  6661. },
  6662. "a" : {
  6663. "type" : "number"
  6664. },
  6665. "b" : {
  6666. "type" : "number"
  6667. }
  6668. }
  6669. }
  6670. """;
  6671. var asyncToolSpecification = new McpServerFeatures.AsyncToolSpecification(
  6672. new Tool("calculator", "Basic calculator", schema),
  6673. (exchange, arguments) -> {
  6674. // Tool implementation
  6675. return Mono.just(new CallToolResult(result, false));
  6676. }
  6677. );
  6678. ```
  6679. </Tab>
  6680. </Tabs>
  6681. The Tool specification includes a Tool definition with `name`, `description`, and `parameter schema` followed by a call handler that implements the tool's logic.
  6682. The function's first argument is `McpAsyncServerExchange` for client interaction, and the second is a map of tool arguments.
  6683. ### Resource Specification
  6684. Specification of a resource with its handler function.
  6685. Resources provide context to AI models by exposing data such as: File contents, Database records, API responses, System information, Application state.
  6686. Example resource specification:
  6687. <Tabs>
  6688. <Tab title="Sync">
  6689. ```java
  6690. // Sync resource specification
  6691. var syncResourceSpecification = new McpServerFeatures.SyncResourceSpecification(
  6692. new Resource("custom://resource", "name", "description", "mime-type", null),
  6693. (exchange, request) -> {
  6694. // Resource read implementation
  6695. return new ReadResourceResult(contents);
  6696. }
  6697. );
  6698. ```
  6699. </Tab>
  6700. <Tab title="Async">
  6701. ```java
  6702. // Async resource specification
  6703. var asyncResourceSpecification = new McpServerFeatures.AsyncResourceSpecification(
  6704. new Resource("custom://resource", "name", "description", "mime-type", null),
  6705. (exchange, request) -> {
  6706. // Resource read implementation
  6707. return Mono.just(new ReadResourceResult(contents));
  6708. }
  6709. );
  6710. ```
  6711. </Tab>
  6712. </Tabs>
  6713. The resource specification comprised of resource definitions and resource read handler.
  6714. The resource definition including `name`, `description`, and `MIME type`.
  6715. The first argument of the function that handles resource read requests is an `McpAsyncServerExchange` upon which the server can
  6716. interact with the connected client.
  6717. The second arguments is a `McpSchema.ReadResourceRequest`.
  6718. ### Prompt Specification
  6719. As part of the [Prompting capabilities](/specification/2024-11-05/server/prompts/), MCP provides a standardized way for servers to expose prompt templates to clients.
  6720. The Prompt Specification is a structured template for AI model interactions that enables consistent message formatting, parameter substitution, context injection, response formatting, and instruction templating.
  6721. <Tabs>
  6722. <Tab title="Sync">
  6723. ```java
  6724. // Sync prompt specification
  6725. var syncPromptSpecification = new McpServerFeatures.SyncPromptSpecification(
  6726. new Prompt("greeting", "description", List.of(
  6727. new PromptArgument("name", "description", true)
  6728. )),
  6729. (exchange, request) -> {
  6730. // Prompt implementation
  6731. return new GetPromptResult(description, messages);
  6732. }
  6733. );
  6734. ```
  6735. </Tab>
  6736. <Tab title="Async">
  6737. ```java
  6738. // Async prompt specification
  6739. var asyncPromptSpecification = new McpServerFeatures.AsyncPromptSpecification(
  6740. new Prompt("greeting", "description", List.of(
  6741. new PromptArgument("name", "description", true)
  6742. )),
  6743. (exchange, request) -> {
  6744. // Prompt implementation
  6745. return Mono.just(new GetPromptResult(description, messages));
  6746. }
  6747. );
  6748. ```
  6749. </Tab>
  6750. </Tabs>
  6751. The prompt definition includes name (identifier for the prompt), description (purpose of the prompt), and list of arguments (parameters for templating).
  6752. The handler function processes requests and returns formatted templates.
  6753. The first argument is `McpAsyncServerExchange` for client interaction, and the second argument is a `GetPromptRequest` instance.
  6754. ### Completion Specification
  6755. As part of the [Completion capabilities](/specification/2025-03-26/server/utilities/completion), MCP provides a provides a standardized way for servers to offer argument autocompletion suggestions for prompts and resource URIs.
  6756. <Tabs>
  6757. <Tab title="Sync">
  6758. ```java
  6759. // Sync completion specification
  6760. var syncCompletionSpecification = new McpServerFeatures.SyncCompletionSpecification(
  6761. new McpSchema.PromptReference("code_review"), (exchange, request) -> {
  6762. // completion implementation ...
  6763. return new McpSchema.CompleteResult(
  6764. new CompleteResult.CompleteCompletion(
  6765. List.of("python", "pytorch", "pyside"),
  6766. 10, // total
  6767. false // hasMore
  6768. ));
  6769. }
  6770. );
  6771. // Create a sync server with completion capabilities
  6772. var mcpServer = McpServer.sync(mcpServerTransportProvider)
  6773. .capabilities(ServerCapabilities.builder()
  6774. .completions() // enable completions support
  6775. // ...
  6776. .build())
  6777. // ...
  6778. .completions(new McpServerFeatures.SyncCompletionSpecification( // register completion specification
  6779. new McpSchema.PromptReference("code_review"), syncCompletionSpecification))
  6780. .build();
  6781. ```
  6782. </Tab>
  6783. <Tab title="Async">
  6784. ```java
  6785. // Async prompt specification
  6786. var asyncCompletionSpecification = new McpServerFeatures.AsyncCompletionSpecification(
  6787. new McpSchema.PromptReference("code_review"), (exchange, request) -> {
  6788. // completion implementation ...
  6789. return Mono.just(new McpSchema.CompleteResult(
  6790. new CompleteResult.CompleteCompletion(
  6791. List.of("python", "pytorch", "pyside"),
  6792. 10, // total
  6793. false // hasMore
  6794. )));
  6795. }
  6796. );
  6797. // Create a async server with completion capabilities
  6798. var mcpServer = McpServer.async(mcpServerTransportProvider)
  6799. .capabilities(ServerCapabilities.builder()
  6800. .completions() // enable completions support
  6801. // ...
  6802. .build())
  6803. // ...
  6804. .completions(new McpServerFeatures.AsyncCompletionSpecification( // register completion specification
  6805. new McpSchema.PromptReference("code_review"), asyncCompletionSpecification))
  6806. .build();
  6807. ```
  6808. </Tab>
  6809. </Tabs>
  6810. The `McpSchema.CompletionReference` definition defines the type (`PromptRefernce` or `ResourceRefernce`) and the identifier for the completion specification (e.g handler).
  6811. The handler function processes requests and returns the complition response.
  6812. The first argument is `McpAsyncServerExchange` for client interaction, and the second argument is a `CompleteRequest` instance.
  6813. Check the [using completion](/sdk/java/mcp-client#using-completion) to learn how to use the completion capabilities on the client side.
  6814. ### Using Sampling from a Server
  6815. To use [Sampling capabilities](/specification/2024-11-05/client/sampling/), connect to a client that supports sampling.
  6816. No special server configuration is needed, but verify client sampling support before making requests.
  6817. Learn about [client sampling support](./mcp-client#sampling-support).
  6818. Once connected to a compatible client, the server can request language model generations:
  6819. <Tabs>
  6820. <Tab title="Sync API">
  6821. ```java
  6822. // Create a server
  6823. McpSyncServer server = McpServer.sync(transportProvider)
  6824. .serverInfo("my-server", "1.0.0")
  6825. .build();
  6826. // Define a tool that uses sampling
  6827. var calculatorTool = new McpServerFeatures.SyncToolSpecification(
  6828. new Tool("ai-calculator", "Performs calculations using AI", schema),
  6829. (exchange, arguments) -> {
  6830. // Check if client supports sampling
  6831. if (exchange.getClientCapabilities().sampling() == null) {
  6832. return new CallToolResult("Client does not support AI capabilities", false);
  6833. }
  6834. // Create a sampling request
  6835. McpSchema.CreateMessageRequest request = McpSchema.CreateMessageRequest.builder()
  6836. .messages(List.of(new McpSchema.SamplingMessage(McpSchema.Role.USER,
  6837. new McpSchema.TextContent("Calculate: " + arguments.get("expression")))
  6838. .modelPreferences(McpSchema.ModelPreferences.builder()
  6839. .hints(List.of(
  6840. McpSchema.ModelHint.of("claude-3-sonnet"),
  6841. McpSchema.ModelHint.of("claude")
  6842. ))
  6843. .intelligencePriority(0.8) // Prioritize intelligence
  6844. .speedPriority(0.5) // Moderate speed importance
  6845. .build())
  6846. .systemPrompt("You are a helpful calculator assistant. Provide only the numerical answer.")
  6847. .maxTokens(100)
  6848. .build();
  6849. // Request sampling from the client
  6850. McpSchema.CreateMessageResult result = exchange.createMessage(request);
  6851. // Process the result
  6852. String answer = result.content().text();
  6853. return new CallToolResult(answer, false);
  6854. }
  6855. );
  6856. // Add the tool to the server
  6857. server.addTool(calculatorTool);
  6858. ```
  6859. </Tab>
  6860. <Tab title="Async API">
  6861. ```java
  6862. // Create a server
  6863. McpAsyncServer server = McpServer.async(transportProvider)
  6864. .serverInfo("my-server", "1.0.0")
  6865. .build();
  6866. // Define a tool that uses sampling
  6867. var calculatorTool = new McpServerFeatures.AsyncToolSpecification(
  6868. new Tool("ai-calculator", "Performs calculations using AI", schema),
  6869. (exchange, arguments) -> {
  6870. // Check if client supports sampling
  6871. if (exchange.getClientCapabilities().sampling() == null) {
  6872. return Mono.just(new CallToolResult("Client does not support AI capabilities", false));
  6873. }
  6874. // Create a sampling request
  6875. McpSchema.CreateMessageRequest request = McpSchema.CreateMessageRequest.builder()
  6876. .content(new McpSchema.TextContent("Calculate: " + arguments.get("expression")))
  6877. .modelPreferences(McpSchema.ModelPreferences.builder()
  6878. .hints(List.of(
  6879. McpSchema.ModelHint.of("claude-3-sonnet"),
  6880. McpSchema.ModelHint.of("claude")
  6881. ))
  6882. .intelligencePriority(0.8) // Prioritize intelligence
  6883. .speedPriority(0.5) // Moderate speed importance
  6884. .build())
  6885. .systemPrompt("You are a helpful calculator assistant. Provide only the numerical answer.")
  6886. .maxTokens(100)
  6887. .build();
  6888. // Request sampling from the client
  6889. return exchange.createMessage(request)
  6890. .map(result -> {
  6891. // Process the result
  6892. String answer = result.content().text();
  6893. return new CallToolResult(answer, false);
  6894. });
  6895. }
  6896. );
  6897. // Add the tool to the server
  6898. server.addTool(calculatorTool)
  6899. .subscribe();
  6900. ```
  6901. </Tab>
  6902. </Tabs>
  6903. The `CreateMessageRequest` object allows you to specify: `Content` - the input text or image for the model,
  6904. `Model Preferences` - hints and priorities for model selection, `System Prompt` - instructions for the model's behavior and
  6905. `Max Tokens` - maximum length of the generated response.
  6906. ### Logging Support
  6907. The server provides structured logging capabilities that allow sending log messages to clients with different severity levels. The
  6908. log notifications can only be sent from within an existing client session, such as tools, resources, and prompts calls.
  6909. For example, we can send a log message from within a tool handler function.
  6910. On the client side, you can register a logging consumer to receive log messages from the server and set the minimum logging level to filter messages.
  6911. ```java
  6912. var mcpClient = McpClient.sync(transport)
  6913. .loggingConsumer(notification -> {
  6914. System.out.println("Received log message: " + notification.data());
  6915. })
  6916. .build();
  6917. mcpClient.initialize();
  6918. mcpClient.setLoggingLevel(McpSchema.LoggingLevel.INFO);
  6919. // Call the tool that sends logging notifications
  6920. CallToolResult result = mcpClient.callTool(new McpSchema.CallToolRequest("logging-test", Map.of()));
  6921. ```
  6922. The server can send log messages using the `McpAsyncServerExchange`/`McpSyncServerExchange` object in the tool/resource/prompt handler function:
  6923. ```java
  6924. var tool = new McpServerFeatures.AsyncToolSpecification(
  6925. new McpSchema.Tool("logging-test", "Test logging notifications", emptyJsonSchema),
  6926. (exchange, request) -> {
  6927. exchange.loggingNotification( // Use the exchange to send log messages
  6928. McpSchema.LoggingMessageNotification.builder()
  6929. .level(McpSchema.LoggingLevel.DEBUG)
  6930. .logger("test-logger")
  6931. .data("Debug message")
  6932. .build())
  6933. .block();
  6934. return Mono.just(new CallToolResult("Logging test completed", false));
  6935. });
  6936. var mcpServer = McpServer.async(mcpServerTransportProvider)
  6937. .serverInfo("test-server", "1.0.0")
  6938. .capabilities(
  6939. ServerCapabilities.builder()
  6940. .logging() // Enable logging support
  6941. .tools(true)
  6942. .build())
  6943. .tools(tool)
  6944. .build();
  6945. ```
  6946. Clients can control the minimum logging level they receive through the `mcpClient.setLoggingLevel(level)` request. Messages below the set level will be filtered out.
  6947. Supported logging levels (in order of increasing severity): DEBUG (0), INFO (1), NOTICE (2), WARNING (3), ERROR (4), CRITICAL (5), ALERT (6), EMERGENCY (7)
  6948. ## Error Handling
  6949. The SDK provides comprehensive error handling through the McpError class, covering protocol compatibility, transport communication, JSON-RPC messaging, tool execution, resource management, prompt handling, timeouts, and connection issues. This unified error handling approach ensures consistent and reliable error management across both synchronous and asynchronous operations.
  6950. # Architecture
  6951. Source: https://modelcontextprotocol.io/specification/2024-11-05/architecture/index
  6952. The Model Context Protocol (MCP) follows a client-host-server architecture where each
  6953. host can run multiple client instances. This architecture enables users to integrate AI
  6954. capabilities across applications while maintaining clear security boundaries and
  6955. isolating concerns. Built on JSON-RPC, MCP provides a stateful session protocol focused
  6956. on context exchange and sampling coordination between clients and servers.
  6957. ## Core Components
  6958. ```mermaid
  6959. graph LR
  6960. subgraph "Application Host Process"
  6961. H[Host]
  6962. C1[Client 1]
  6963. C2[Client 2]
  6964. C3[Client 3]
  6965. H --> C1
  6966. H --> C2
  6967. H --> C3
  6968. end
  6969. subgraph "Local machine"
  6970. S1[Server 1<br>Files & Git]
  6971. S2[Server 2<br>Database]
  6972. R1[("Local<br>Resource A")]
  6973. R2[("Local<br>Resource B")]
  6974. C1 --> S1
  6975. C2 --> S2
  6976. S1 <--> R1
  6977. S2 <--> R2
  6978. end
  6979. subgraph "Internet"
  6980. S3[Server 3<br>External APIs]
  6981. R3[("Remote<br>Resource C")]
  6982. C3 --> S3
  6983. S3 <--> R3
  6984. end
  6985. ```
  6986. ### Host
  6987. The host process acts as the container and coordinator:
  6988. * Creates and manages multiple client instances
  6989. * Controls client connection permissions and lifecycle
  6990. * Enforces security policies and consent requirements
  6991. * Handles user authorization decisions
  6992. * Coordinates AI/LLM integration and sampling
  6993. * Manages context aggregation across clients
  6994. ### Clients
  6995. Each client is created by the host and maintains an isolated server connection:
  6996. * Establishes one stateful session per server
  6997. * Handles protocol negotiation and capability exchange
  6998. * Routes protocol messages bidirectionally
  6999. * Manages subscriptions and notifications
  7000. * Maintains security boundaries between servers
  7001. A host application creates and manages multiple clients, with each client having a 1:1
  7002. relationship with a particular server.
  7003. ### Servers
  7004. Servers provide specialized context and capabilities:
  7005. * Expose resources, tools and prompts via MCP primitives
  7006. * Operate independently with focused responsibilities
  7007. * Request sampling through client interfaces
  7008. * Must respect security constraints
  7009. * Can be local processes or remote services
  7010. ## Design Principles
  7011. MCP is built on several key design principles that inform its architecture and
  7012. implementation:
  7013. 1. **Servers should be extremely easy to build**
  7014. * Host applications handle complex orchestration responsibilities
  7015. * Servers focus on specific, well-defined capabilities
  7016. * Simple interfaces minimize implementation overhead
  7017. * Clear separation enables maintainable code
  7018. 2. **Servers should be highly composable**
  7019. * Each server provides focused functionality in isolation
  7020. * Multiple servers can be combined seamlessly
  7021. * Shared protocol enables interoperability
  7022. * Modular design supports extensibility
  7023. 3. **Servers should not be able to read the whole conversation, nor "see into" other
  7024. servers**
  7025. * Servers receive only necessary contextual information
  7026. * Full conversation history stays with the host
  7027. * Each server connection maintains isolation
  7028. * Cross-server interactions are controlled by the host
  7029. * Host process enforces security boundaries
  7030. 4. **Features can be added to servers and clients progressively**
  7031. * Core protocol provides minimal required functionality
  7032. * Additional capabilities can be negotiated as needed
  7033. * Servers and clients evolve independently
  7034. * Protocol designed for future extensibility
  7035. * Backwards compatibility is maintained
  7036. ## Message Types
  7037. MCP defines three core message types based on
  7038. [JSON-RPC 2.0](https://www.jsonrpc.org/specification):
  7039. * **Requests**: Bidirectional messages with method and parameters expecting a response
  7040. * **Responses**: Successful results or errors matching specific request IDs
  7041. * **Notifications**: One-way messages requiring no response
  7042. Each message type follows the JSON-RPC 2.0 specification for structure and delivery
  7043. semantics.
  7044. ## Capability Negotiation
  7045. The Model Context Protocol uses a capability-based negotiation system where clients and
  7046. servers explicitly declare their supported features during initialization. Capabilities
  7047. determine which protocol features and primitives are available during a session.
  7048. * Servers declare capabilities like resource subscriptions, tool support, and prompt
  7049. templates
  7050. * Clients declare capabilities like sampling support and notification handling
  7051. * Both parties must respect declared capabilities throughout the session
  7052. * Additional capabilities can be negotiated through extensions to the protocol
  7053. ```mermaid
  7054. sequenceDiagram
  7055. participant Host
  7056. participant Client
  7057. participant Server
  7058. Host->>+Client: Initialize client
  7059. Client->>+Server: Initialize session with capabilities
  7060. Server-->>Client: Respond with supported capabilities
  7061. Note over Host,Server: Active Session with Negotiated Features
  7062. loop Client Requests
  7063. Host->>Client: User- or model-initiated action
  7064. Client->>Server: Request (tools/resources)
  7065. Server-->>Client: Response
  7066. Client-->>Host: Update UI or respond to model
  7067. end
  7068. loop Server Requests
  7069. Server->>Client: Request (sampling)
  7070. Client->>Host: Forward to AI
  7071. Host-->>Client: AI response
  7072. Client-->>Server: Response
  7073. end
  7074. loop Notifications
  7075. Server--)Client: Resource updates
  7076. Client--)Server: Status changes
  7077. end
  7078. Host->>Client: Terminate
  7079. Client->>-Server: End session
  7080. deactivate Server
  7081. ```
  7082. Each capability unlocks specific protocol features for use during the session. For
  7083. example:
  7084. * Implemented [server features](/specification/2024-11-05/server) must be
  7085. advertised in the server's capabilities
  7086. * Emitting resource subscription notifications requires the server to declare
  7087. subscription support
  7088. * Tool invocation requires the server to declare tool capabilities
  7089. * [Sampling](/specification/2024-11-05/client) requires the client to
  7090. declare support in its capabilities
  7091. This capability negotiation ensures clients and servers have a clear understanding of
  7092. supported functionality while maintaining protocol extensibility.
  7093. # Overview
  7094. Source: https://modelcontextprotocol.io/specification/2024-11-05/basic/index
  7095. <Info>**Protocol Revision**: 2024-11-05</Info>
  7096. All messages between MCP clients and servers **MUST** follow the
  7097. [JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines
  7098. three fundamental types of messages:
  7099. | Type | Description | Requirements |
  7100. | --------------- | -------------------------------------- | -------------------------------------- |
  7101. | `Requests` | Messages sent to initiate an operation | Must include unique ID and method name |
  7102. | `Responses` | Messages sent in reply to requests | Must include same ID as request |
  7103. | `Notifications` | One-way messages with no reply | Must not include an ID |
  7104. **Responses** are further sub-categorized as either **successful results** or **errors**.
  7105. Results can follow any JSON object structure, while errors must include an error code and
  7106. message at minimum.
  7107. ## Protocol Layers
  7108. The Model Context Protocol consists of several key components that work together:
  7109. * **Base Protocol**: Core JSON-RPC message types
  7110. * **Lifecycle Management**: Connection initialization, capability negotiation, and
  7111. session control
  7112. * **Server Features**: Resources, prompts, and tools exposed by servers
  7113. * **Client Features**: Sampling and root directory lists provided by clients
  7114. * **Utilities**: Cross-cutting concerns like logging and argument completion
  7115. All implementations **MUST** support the base protocol and lifecycle management
  7116. components. Other components **MAY** be implemented based on the specific needs of the
  7117. application.
  7118. These protocol layers establish clear separation of concerns while enabling rich
  7119. interactions between clients and servers. The modular design allows implementations to
  7120. support exactly the features they need.
  7121. See the following pages for more details on the different components:
  7122. <CardGroup cols={3}>
  7123. <Card title="Lifecycle" icon="arrows-rotate" href="/specification/2024-11-05/basic/lifecycle" />
  7124. <Card title="Resources" icon="file-lines" href="/specification/2024-11-05/server/resources" />
  7125. <Card title="Prompts" icon="message" href="/specification/2024-11-05/server/prompts" />
  7126. <Card title="Tools" icon="wrench" href="/specification/2024-11-05/server/tools" />
  7127. <Card title="Logging" icon="rectangle-list" href="/specification/2024-11-05/server/utilities/logging" />
  7128. <Card title="Sampling" icon="code" href="/specification/2024-11-05/client/sampling" />
  7129. </CardGroup>
  7130. ## Auth
  7131. Authentication and authorization are not currently part of the core MCP specification,
  7132. but we are considering ways to introduce them in future. Join us in
  7133. [GitHub Discussions](https://github.com/modelcontextprotocol/specification/discussions)
  7134. to help shape the future of the protocol!
  7135. Clients and servers **MAY** negotiate their own custom authentication and authorization
  7136. strategies.
  7137. ## Schema
  7138. The full specification of the protocol is defined as a
  7139. [TypeScript schema](http://github.com/modelcontextprotocol/specification/tree/main/schema/2024-11-05/schema.ts).
  7140. This is the source of truth for all protocol messages and structures.
  7141. There is also a
  7142. [JSON Schema](http://github.com/modelcontextprotocol/specification/tree/main/schema/2024-11-05/schema.json),
  7143. which is automatically generated from the TypeScript source of truth, for use with
  7144. various automated tooling.
  7145. # Lifecycle
  7146. Source: https://modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle
  7147. <Info>**Protocol Revision**: 2024-11-05</Info>
  7148. The Model Context Protocol (MCP) defines a rigorous lifecycle for client-server
  7149. connections that ensures proper capability negotiation and state management.
  7150. 1. **Initialization**: Capability negotiation and protocol version agreement
  7151. 2. **Operation**: Normal protocol communication
  7152. 3. **Shutdown**: Graceful termination of the connection
  7153. ```mermaid
  7154. sequenceDiagram
  7155. participant Client
  7156. participant Server
  7157. Note over Client,Server: Initialization Phase
  7158. activate Client
  7159. Client->>+Server: initialize request
  7160. Server-->>Client: initialize response
  7161. Client--)Server: initialized notification
  7162. Note over Client,Server: Operation Phase
  7163. rect rgb(200, 220, 250)
  7164. note over Client,Server: Normal protocol operations
  7165. end
  7166. Note over Client,Server: Shutdown
  7167. Client--)-Server: Disconnect
  7168. deactivate Server
  7169. Note over Client,Server: Connection closed
  7170. ```
  7171. ## Lifecycle Phases
  7172. ### Initialization
  7173. The initialization phase **MUST** be the first interaction between client and server.
  7174. During this phase, the client and server:
  7175. * Establish protocol version compatibility
  7176. * Exchange and negotiate capabilities
  7177. * Share implementation details
  7178. The client **MUST** initiate this phase by sending an `initialize` request containing:
  7179. * Protocol version supported
  7180. * Client capabilities
  7181. * Client implementation information
  7182. ```json
  7183. {
  7184. "jsonrpc": "2.0",
  7185. "id": 1,
  7186. "method": "initialize",
  7187. "params": {
  7188. "protocolVersion": "2024-11-05",
  7189. "capabilities": {
  7190. "roots": {
  7191. "listChanged": true
  7192. },
  7193. "sampling": {}
  7194. },
  7195. "clientInfo": {
  7196. "name": "ExampleClient",
  7197. "version": "1.0.0"
  7198. }
  7199. }
  7200. }
  7201. ```
  7202. The server **MUST** respond with its own capabilities and information:
  7203. ```json
  7204. {
  7205. "jsonrpc": "2.0",
  7206. "id": 1,
  7207. "result": {
  7208. "protocolVersion": "2024-11-05",
  7209. "capabilities": {
  7210. "logging": {},
  7211. "prompts": {
  7212. "listChanged": true
  7213. },
  7214. "resources": {
  7215. "subscribe": true,
  7216. "listChanged": true
  7217. },
  7218. "tools": {
  7219. "listChanged": true
  7220. }
  7221. },
  7222. "serverInfo": {
  7223. "name": "ExampleServer",
  7224. "version": "1.0.0"
  7225. }
  7226. }
  7227. }
  7228. ```
  7229. After successful initialization, the client **MUST** send an `initialized` notification
  7230. to indicate it is ready to begin normal operations:
  7231. ```json
  7232. {
  7233. "jsonrpc": "2.0",
  7234. "method": "notifications/initialized"
  7235. }
  7236. ```
  7237. * The client **SHOULD NOT** send requests other than
  7238. [pings](/specification/2024-11-05/basic/utilities/ping) before the server
  7239. has responded to the `initialize` request.
  7240. * The server **SHOULD NOT** send requests other than
  7241. [pings](/specification/2024-11-05/basic/utilities/ping) and
  7242. [logging](/specification/2024-11-05/server/utilities/logging) before
  7243. receiving the `initialized` notification.
  7244. #### Version Negotiation
  7245. In the `initialize` request, the client **MUST** send a protocol version it supports.
  7246. This **SHOULD** be the *latest* version supported by the client.
  7247. If the server supports the requested protocol version, it **MUST** respond with the same
  7248. version. Otherwise, the server **MUST** respond with another protocol version it
  7249. supports. This **SHOULD** be the *latest* version supported by the server.
  7250. If the client does not support the version in the server's response, it **SHOULD**
  7251. disconnect.
  7252. #### Capability Negotiation
  7253. Client and server capabilities establish which optional protocol features will be
  7254. available during the session.
  7255. Key capabilities include:
  7256. | Category | Capability | Description |
  7257. | -------- | -------------- | ----------------------------------------------------------------------------------- |
  7258. | Client | `roots` | Ability to provide filesystem [roots](/specification/2024-11-05/client/roots) |
  7259. | Client | `sampling` | Support for LLM [sampling](/specification/2024-11-05/client/sampling) requests |
  7260. | Client | `experimental` | Describes support for non-standard experimental features |
  7261. | Server | `prompts` | Offers [prompt templates](/specification/2024-11-05/server/prompts) |
  7262. | Server | `resources` | Provides readable [resources](/specification/2024-11-05/server/resources) |
  7263. | Server | `tools` | Exposes callable [tools](/specification/2024-11-05/server/tools) |
  7264. | Server | `logging` | Emits structured [log messages](/specification/2024-11-05/server/utilities/logging) |
  7265. | Server | `experimental` | Describes support for non-standard experimental features |
  7266. Capability objects can describe sub-capabilities like:
  7267. * `listChanged`: Support for list change notifications (for prompts, resources, and
  7268. tools)
  7269. * `subscribe`: Support for subscribing to individual items' changes (resources only)
  7270. ### Operation
  7271. During the operation phase, the client and server exchange messages according to the
  7272. negotiated capabilities.
  7273. Both parties **SHOULD**:
  7274. * Respect the negotiated protocol version
  7275. * Only use capabilities that were successfully negotiated
  7276. ### Shutdown
  7277. During the shutdown phase, one side (usually the client) cleanly terminates the protocol
  7278. connection. No specific shutdown messages are defined—instead, the underlying transport
  7279. mechanism should be used to signal connection termination:
  7280. #### stdio
  7281. For the stdio [transport](/specification/2024-11-05/basic/transports), the
  7282. client **SHOULD** initiate shutdown by:
  7283. 1. First, closing the input stream to the child process (the server)
  7284. 2. Waiting for the server to exit, or sending `SIGTERM` if the server does not exit
  7285. within a reasonable time
  7286. 3. Sending `SIGKILL` if the server does not exit within a reasonable time after `SIGTERM`
  7287. The server **MAY** initiate shutdown by closing its output stream to the client and
  7288. exiting.
  7289. #### HTTP
  7290. For HTTP [transports](/specification/2024-11-05/basic/transports), shutdown
  7291. is indicated by closing the associated HTTP connection(s).
  7292. ## Error Handling
  7293. Implementations **SHOULD** be prepared to handle these error cases:
  7294. * Protocol version mismatch
  7295. * Failure to negotiate required capabilities
  7296. * Initialize request timeout
  7297. * Shutdown timeout
  7298. Implementations **SHOULD** implement appropriate timeouts for all requests, to prevent
  7299. hung connections and resource exhaustion.
  7300. Example initialization error:
  7301. ```json
  7302. {
  7303. "jsonrpc": "2.0",
  7304. "id": 1,
  7305. "error": {
  7306. "code": -32602,
  7307. "message": "Unsupported protocol version",
  7308. "data": {
  7309. "supported": ["2024-11-05"],
  7310. "requested": "1.0.0"
  7311. }
  7312. }
  7313. }
  7314. ```
  7315. # Messages
  7316. Source: https://modelcontextprotocol.io/specification/2024-11-05/basic/messages
  7317. <Info>**Protocol Revision**: 2024-11-05</Info>
  7318. All messages in MCP **MUST** follow the
  7319. [JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines
  7320. three types of messages:
  7321. ## Requests
  7322. Requests are sent from the client to the server or vice versa.
  7323. ```typescript
  7324. {
  7325. jsonrpc: "2.0";
  7326. id: string | number;
  7327. method: string;
  7328. params?: {
  7329. [key: string]: unknown;
  7330. };
  7331. }
  7332. ```
  7333. * Requests **MUST** include a string or integer ID.
  7334. * Unlike base JSON-RPC, the ID **MUST NOT** be `null`.
  7335. * The request ID **MUST NOT** have been previously used by the requestor within the same
  7336. session.
  7337. ## Responses
  7338. Responses are sent in reply to requests.
  7339. ```typescript
  7340. {
  7341. jsonrpc: "2.0";
  7342. id: string | number;
  7343. result?: {
  7344. [key: string]: unknown;
  7345. }
  7346. error?: {
  7347. code: number;
  7348. message: string;
  7349. data?: unknown;
  7350. }
  7351. }
  7352. ```
  7353. * Responses **MUST** include the same ID as the request they correspond to.
  7354. * Either a `result` or an `error` **MUST** be set. A response **MUST NOT** set both.
  7355. * Error codes **MUST** be integers.
  7356. ## Notifications
  7357. Notifications are sent from the client to the server or vice versa. They do not expect a
  7358. response.
  7359. ```typescript
  7360. {
  7361. jsonrpc: "2.0";
  7362. method: string;
  7363. params?: {
  7364. [key: string]: unknown;
  7365. };
  7366. }
  7367. ```
  7368. * Notifications **MUST NOT** include an ID.
  7369. # Transports
  7370. Source: https://modelcontextprotocol.io/specification/2024-11-05/basic/transports
  7371. <Info>**Protocol Revision**: 2024-11-05</Info>
  7372. MCP currently defines two standard transport mechanisms for client-server communication:
  7373. 1. [stdio](#stdio), communication over standard in and standard out
  7374. 2. [HTTP with Server-Sent Events](#http-with-sse) (SSE)
  7375. Clients **SHOULD** support stdio whenever possible.
  7376. It is also possible for clients and servers to implement
  7377. [custom transports](#custom-transports) in a pluggable fashion.
  7378. ## stdio
  7379. In the **stdio** transport:
  7380. * The client launches the MCP server as a subprocess.
  7381. * The server receives JSON-RPC messages on its standard input (`stdin`) and writes
  7382. responses to its standard output (`stdout`).
  7383. * Messages are delimited by newlines, and **MUST NOT** contain embedded newlines.
  7384. * The server **MAY** write UTF-8 strings to its standard error (`stderr`) for logging
  7385. purposes. Clients **MAY** capture, forward, or ignore this logging.
  7386. * The server **MUST NOT** write anything to its `stdout` that is not a valid MCP message.
  7387. * The client **MUST NOT** write anything to the server's `stdin` that is not a valid MCP
  7388. message.
  7389. ```mermaid
  7390. sequenceDiagram
  7391. participant Client
  7392. participant Server Process
  7393. Client->>+Server Process: Launch subprocess
  7394. loop Message Exchange
  7395. Client->>Server Process: Write to stdin
  7396. Server Process->>Client: Write to stdout
  7397. Server Process--)Client: Optional logs on stderr
  7398. end
  7399. Client->>Server Process: Close stdin, terminate subprocess
  7400. deactivate Server Process
  7401. ```
  7402. ## HTTP with SSE
  7403. In the **SSE** transport, the server operates as an independent process that can handle
  7404. multiple client connections.
  7405. #### Security Warning
  7406. When implementing HTTP with SSE transport:
  7407. 1. Servers **MUST** validate the `Origin` header on all incoming connections to prevent DNS rebinding attacks
  7408. 2. When running locally, servers **SHOULD** bind only to localhost (127.0.0.1) rather than all network interfaces (0.0.0.0)
  7409. 3. Servers **SHOULD** implement proper authentication for all connections
  7410. Without these protections, attackers could use DNS rebinding to interact with local MCP servers from remote websites.
  7411. The server **MUST** provide two endpoints:
  7412. 1. An SSE endpoint, for clients to establish a connection and receive messages from the
  7413. server
  7414. 2. A regular HTTP POST endpoint for clients to send messages to the server
  7415. When a client connects, the server **MUST** send an `endpoint` event containing a URI for
  7416. the client to use for sending messages. All subsequent client messages **MUST** be sent
  7417. as HTTP POST requests to this endpoint.
  7418. Server messages are sent as SSE `message` events, with the message content encoded as
  7419. JSON in the event data.
  7420. ```mermaid
  7421. sequenceDiagram
  7422. participant Client
  7423. participant Server
  7424. Client->>Server: Open SSE connection
  7425. Server->>Client: endpoint event
  7426. loop Message Exchange
  7427. Client->>Server: HTTP POST messages
  7428. Server->>Client: SSE message events
  7429. end
  7430. Client->>Server: Close SSE connection
  7431. ```
  7432. ## Custom Transports
  7433. Clients and servers **MAY** implement additional custom transport mechanisms to suit
  7434. their specific needs. The protocol is transport-agnostic and can be implemented over any
  7435. communication channel that supports bidirectional message exchange.
  7436. Implementers who choose to support custom transports **MUST** ensure they preserve the
  7437. JSON-RPC message format and lifecycle requirements defined by MCP. Custom transports
  7438. **SHOULD** document their specific connection establishment and message exchange patterns
  7439. to aid interoperability.
  7440. # Cancellation
  7441. Source: https://modelcontextprotocol.io/specification/2024-11-05/basic/utilities/cancellation
  7442. <Info>**Protocol Revision**: 2024-11-05</Info>
  7443. The Model Context Protocol (MCP) supports optional cancellation of in-progress requests
  7444. through notification messages. Either side can send a cancellation notification to
  7445. indicate that a previously-issued request should be terminated.
  7446. ## Cancellation Flow
  7447. When a party wants to cancel an in-progress request, it sends a `notifications/cancelled`
  7448. notification containing:
  7449. * The ID of the request to cancel
  7450. * An optional reason string that can be logged or displayed
  7451. ```json
  7452. {
  7453. "jsonrpc": "2.0",
  7454. "method": "notifications/cancelled",
  7455. "params": {
  7456. "requestId": "123",
  7457. "reason": "User requested cancellation"
  7458. }
  7459. }
  7460. ```
  7461. ## Behavior Requirements
  7462. 1. Cancellation notifications **MUST** only reference requests that:
  7463. * Were previously issued in the same direction
  7464. * Are believed to still be in-progress
  7465. 2. The `initialize` request **MUST NOT** be cancelled by clients
  7466. 3. Receivers of cancellation notifications **SHOULD**:
  7467. * Stop processing the cancelled request
  7468. * Free associated resources
  7469. * Not send a response for the cancelled request
  7470. 4. Receivers **MAY** ignore cancellation notifications if:
  7471. * The referenced request is unknown
  7472. * Processing has already completed
  7473. * The request cannot be cancelled
  7474. 5. The sender of the cancellation notification **SHOULD** ignore any response to the
  7475. request that arrives afterward
  7476. ## Timing Considerations
  7477. Due to network latency, cancellation notifications may arrive after request processing
  7478. has completed, and potentially after a response has already been sent.
  7479. Both parties **MUST** handle these race conditions gracefully:
  7480. ```mermaid
  7481. sequenceDiagram
  7482. participant Client
  7483. participant Server
  7484. Client->>Server: Request (ID: 123)
  7485. Note over Server: Processing starts
  7486. Client--)Server: notifications/cancelled (ID: 123)
  7487. alt
  7488. Note over Server: Processing may have<br/>completed before<br/>cancellation arrives
  7489. else If not completed
  7490. Note over Server: Stop processing
  7491. end
  7492. ```
  7493. ## Implementation Notes
  7494. * Both parties **SHOULD** log cancellation reasons for debugging
  7495. * Application UIs **SHOULD** indicate when cancellation is requested
  7496. ## Error Handling
  7497. Invalid cancellation notifications **SHOULD** be ignored:
  7498. * Unknown request IDs
  7499. * Already completed requests
  7500. * Malformed notifications
  7501. This maintains the "fire and forget" nature of notifications while allowing for race
  7502. conditions in asynchronous communication.
  7503. # Ping
  7504. Source: https://modelcontextprotocol.io/specification/2024-11-05/basic/utilities/ping
  7505. <Info>**Protocol Revision**: 2024-11-05</Info>
  7506. The Model Context Protocol includes an optional ping mechanism that allows either party
  7507. to verify that their counterpart is still responsive and the connection is alive.
  7508. ## Overview
  7509. The ping functionality is implemented through a simple request/response pattern. Either
  7510. the client or server can initiate a ping by sending a `ping` request.
  7511. ## Message Format
  7512. A ping request is a standard JSON-RPC request with no parameters:
  7513. ```json
  7514. {
  7515. "jsonrpc": "2.0",
  7516. "id": "123",
  7517. "method": "ping"
  7518. }
  7519. ```
  7520. ## Behavior Requirements
  7521. 1. The receiver **MUST** respond promptly with an empty response:
  7522. ```json
  7523. {
  7524. "jsonrpc": "2.0",
  7525. "id": "123",
  7526. "result": {}
  7527. }
  7528. ```
  7529. 2. If no response is received within a reasonable timeout period, the sender **MAY**:
  7530. * Consider the connection stale
  7531. * Terminate the connection
  7532. * Attempt reconnection procedures
  7533. ## Usage Patterns
  7534. ```mermaid
  7535. sequenceDiagram
  7536. participant Sender
  7537. participant Receiver
  7538. Sender->>Receiver: ping request
  7539. Receiver->>Sender: empty response
  7540. ```
  7541. ## Implementation Considerations
  7542. * Implementations **SHOULD** periodically issue pings to detect connection health
  7543. * The frequency of pings **SHOULD** be configurable
  7544. * Timeouts **SHOULD** be appropriate for the network environment
  7545. * Excessive pinging **SHOULD** be avoided to reduce network overhead
  7546. ## Error Handling
  7547. * Timeouts **SHOULD** be treated as connection failures
  7548. * Multiple failed pings **MAY** trigger connection reset
  7549. * Implementations **SHOULD** log ping failures for diagnostics
  7550. # Progress
  7551. Source: https://modelcontextprotocol.io/specification/2024-11-05/basic/utilities/progress
  7552. <Info>**Protocol Revision**: 2024-11-05</Info>
  7553. The Model Context Protocol (MCP) supports optional progress tracking for long-running
  7554. operations through notification messages. Either side can send progress notifications to
  7555. provide updates about operation status.
  7556. ## Progress Flow
  7557. When a party wants to *receive* progress updates for a request, it includes a
  7558. `progressToken` in the request metadata.
  7559. * Progress tokens **MUST** be a string or integer value
  7560. * Progress tokens can be chosen by the sender using any means, but **MUST** be unique
  7561. across all active requests.
  7562. ```json
  7563. {
  7564. "jsonrpc": "2.0",
  7565. "id": 1,
  7566. "method": "some_method",
  7567. "params": {
  7568. "_meta": {
  7569. "progressToken": "abc123"
  7570. }
  7571. }
  7572. }
  7573. ```
  7574. The receiver **MAY** then send progress notifications containing:
  7575. * The original progress token
  7576. * The current progress value so far
  7577. * An optional "total" value
  7578. ```json
  7579. {
  7580. "jsonrpc": "2.0",
  7581. "method": "notifications/progress",
  7582. "params": {
  7583. "progressToken": "abc123",
  7584. "progress": 50,
  7585. "total": 100
  7586. }
  7587. }
  7588. ```
  7589. * The `progress` value **MUST** increase with each notification, even if the total is
  7590. unknown.
  7591. * The `progress` and the `total` values **MAY** be floating point.
  7592. ## Behavior Requirements
  7593. 1. Progress notifications **MUST** only reference tokens that:
  7594. * Were provided in an active request
  7595. * Are associated with an in-progress operation
  7596. 2. Receivers of progress requests **MAY**:
  7597. * Choose not to send any progress notifications
  7598. * Send notifications at whatever frequency they deem appropriate
  7599. * Omit the total value if unknown
  7600. ```mermaid
  7601. sequenceDiagram
  7602. participant Sender
  7603. participant Receiver
  7604. Note over Sender,Receiver: Request with progress token
  7605. Sender->>Receiver: Method request with progressToken
  7606. Note over Sender,Receiver: Progress updates
  7607. loop Progress Updates
  7608. Receiver-->>Sender: Progress notification (0.2/1.0)
  7609. Receiver-->>Sender: Progress notification (0.6/1.0)
  7610. Receiver-->>Sender: Progress notification (1.0/1.0)
  7611. end
  7612. Note over Sender,Receiver: Operation complete
  7613. Receiver->>Sender: Method response
  7614. ```
  7615. ## Implementation Notes
  7616. * Senders and receivers **SHOULD** track active progress tokens
  7617. * Both parties **SHOULD** implement rate limiting to prevent flooding
  7618. * Progress notifications **MUST** stop after completion
  7619. # Roots
  7620. Source: https://modelcontextprotocol.io/specification/2024-11-05/client/roots
  7621. <Info>**Protocol Revision**: 2024-11-05</Info>
  7622. The Model Context Protocol (MCP) provides a standardized way for clients to expose
  7623. filesystem "roots" to servers. Roots define the boundaries of where servers can operate
  7624. within the filesystem, allowing them to understand which directories and files they have
  7625. access to. Servers can request the list of roots from supporting clients and receive
  7626. notifications when that list changes.
  7627. ## User Interaction Model
  7628. Roots in MCP are typically exposed through workspace or project configuration interfaces.
  7629. For example, implementations could offer a workspace/project picker that allows users to
  7630. select directories and files the server should have access to. This can be combined with
  7631. automatic workspace detection from version control systems or project files.
  7632. However, implementations are free to expose roots through any interface pattern that
  7633. suits their needs—the protocol itself does not mandate any specific user
  7634. interaction model.
  7635. ## Capabilities
  7636. Clients that support roots **MUST** declare the `roots` capability during
  7637. [initialization](/specification/2024-11-05/basic/lifecycle#initialization):
  7638. ```json
  7639. {
  7640. "capabilities": {
  7641. "roots": {
  7642. "listChanged": true
  7643. }
  7644. }
  7645. }
  7646. ```
  7647. `listChanged` indicates whether the client will emit notifications when the list of roots
  7648. changes.
  7649. ## Protocol Messages
  7650. ### Listing Roots
  7651. To retrieve roots, servers send a `roots/list` request:
  7652. **Request:**
  7653. ```json
  7654. {
  7655. "jsonrpc": "2.0",
  7656. "id": 1,
  7657. "method": "roots/list"
  7658. }
  7659. ```
  7660. **Response:**
  7661. ```json
  7662. {
  7663. "jsonrpc": "2.0",
  7664. "id": 1,
  7665. "result": {
  7666. "roots": [
  7667. {
  7668. "uri": "file:///home/user/projects/myproject",
  7669. "name": "My Project"
  7670. }
  7671. ]
  7672. }
  7673. }
  7674. ```
  7675. ### Root List Changes
  7676. When roots change, clients that support `listChanged` **MUST** send a notification:
  7677. ```json
  7678. {
  7679. "jsonrpc": "2.0",
  7680. "method": "notifications/roots/list_changed"
  7681. }
  7682. ```
  7683. ## Message Flow
  7684. ```mermaid
  7685. sequenceDiagram
  7686. participant Server
  7687. participant Client
  7688. Note over Server,Client: Discovery
  7689. Server->>Client: roots/list
  7690. Client-->>Server: Available roots
  7691. Note over Server,Client: Changes
  7692. Client--)Server: notifications/roots/list_changed
  7693. Server->>Client: roots/list
  7694. Client-->>Server: Updated roots
  7695. ```
  7696. ## Data Types
  7697. ### Root
  7698. A root definition includes:
  7699. * `uri`: Unique identifier for the root. This **MUST** be a `file://` URI in the current
  7700. specification.
  7701. * `name`: Optional human-readable name for display purposes.
  7702. Example roots for different use cases:
  7703. #### Project Directory
  7704. ```json
  7705. {
  7706. "uri": "file:///home/user/projects/myproject",
  7707. "name": "My Project"
  7708. }
  7709. ```
  7710. #### Multiple Repositories
  7711. ```json
  7712. [
  7713. {
  7714. "uri": "file:///home/user/repos/frontend",
  7715. "name": "Frontend Repository"
  7716. },
  7717. {
  7718. "uri": "file:///home/user/repos/backend",
  7719. "name": "Backend Repository"
  7720. }
  7721. ]
  7722. ```
  7723. ## Error Handling
  7724. Clients **SHOULD** return standard JSON-RPC errors for common failure cases:
  7725. * Client does not support roots: `-32601` (Method not found)
  7726. * Internal errors: `-32603`
  7727. Example error:
  7728. ```json
  7729. {
  7730. "jsonrpc": "2.0",
  7731. "id": 1,
  7732. "error": {
  7733. "code": -32601,
  7734. "message": "Roots not supported",
  7735. "data": {
  7736. "reason": "Client does not have roots capability"
  7737. }
  7738. }
  7739. }
  7740. ```
  7741. ## Security Considerations
  7742. 1. Clients **MUST**:
  7743. * Only expose roots with appropriate permissions
  7744. * Validate all root URIs to prevent path traversal
  7745. * Implement proper access controls
  7746. * Monitor root accessibility
  7747. 2. Servers **SHOULD**:
  7748. * Handle cases where roots become unavailable
  7749. * Respect root boundaries during operations
  7750. * Validate all paths against provided roots
  7751. ## Implementation Guidelines
  7752. 1. Clients **SHOULD**:
  7753. * Prompt users for consent before exposing roots to servers
  7754. * Provide clear user interfaces for root management
  7755. * Validate root accessibility before exposing
  7756. * Monitor for root changes
  7757. 2. Servers **SHOULD**:
  7758. * Check for roots capability before usage
  7759. * Handle root list changes gracefully
  7760. * Respect root boundaries in operations
  7761. * Cache root information appropriately
  7762. # Sampling
  7763. Source: https://modelcontextprotocol.io/specification/2024-11-05/client/sampling
  7764. <Info>**Protocol Revision**: 2024-11-05</Info>
  7765. The Model Context Protocol (MCP) provides a standardized way for servers to request LLM
  7766. sampling ("completions" or "generations") from language models via clients. This flow
  7767. allows clients to maintain control over model access, selection, and permissions while
  7768. enabling servers to leverage AI capabilities—with no server API keys necessary.
  7769. Servers can request text or image-based interactions and optionally include context from
  7770. MCP servers in their prompts.
  7771. ## User Interaction Model
  7772. Sampling in MCP allows servers to implement agentic behaviors, by enabling LLM calls to
  7773. occur *nested* inside other MCP server features.
  7774. Implementations are free to expose sampling through any interface pattern that suits
  7775. their needs—the protocol itself does not mandate any specific user interaction
  7776. model.
  7777. <Warning>
  7778. For trust & safety and security, there **SHOULD** always
  7779. be a human in the loop with the ability to deny sampling requests.
  7780. Applications **SHOULD**:
  7781. * Provide UI that makes it easy and intuitive to review sampling requests
  7782. * Allow users to view and edit prompts before sending
  7783. * Present generated responses for review before delivery
  7784. </Warning>
  7785. ## Capabilities
  7786. Clients that support sampling **MUST** declare the `sampling` capability during
  7787. [initialization](/specification/2024-11-05/basic/lifecycle#initialization):
  7788. ```json
  7789. {
  7790. "capabilities": {
  7791. "sampling": {}
  7792. }
  7793. }
  7794. ```
  7795. ## Protocol Messages
  7796. ### Creating Messages
  7797. To request a language model generation, servers send a `sampling/createMessage` request:
  7798. **Request:**
  7799. ```json
  7800. {
  7801. "jsonrpc": "2.0",
  7802. "id": 1,
  7803. "method": "sampling/createMessage",
  7804. "params": {
  7805. "messages": [
  7806. {
  7807. "role": "user",
  7808. "content": {
  7809. "type": "text",
  7810. "text": "What is the capital of France?"
  7811. }
  7812. }
  7813. ],
  7814. "modelPreferences": {
  7815. "hints": [
  7816. {
  7817. "name": "claude-3-sonnet"
  7818. }
  7819. ],
  7820. "intelligencePriority": 0.8,
  7821. "speedPriority": 0.5
  7822. },
  7823. "systemPrompt": "You are a helpful assistant.",
  7824. "maxTokens": 100
  7825. }
  7826. }
  7827. ```
  7828. **Response:**
  7829. ```json
  7830. {
  7831. "jsonrpc": "2.0",
  7832. "id": 1,
  7833. "result": {
  7834. "role": "assistant",
  7835. "content": {
  7836. "type": "text",
  7837. "text": "The capital of France is Paris."
  7838. },
  7839. "model": "claude-3-sonnet-20240307",
  7840. "stopReason": "endTurn"
  7841. }
  7842. }
  7843. ```
  7844. ## Message Flow
  7845. ```mermaid
  7846. sequenceDiagram
  7847. participant Server
  7848. participant Client
  7849. participant User
  7850. participant LLM
  7851. Note over Server,Client: Server initiates sampling
  7852. Server->>Client: sampling/createMessage
  7853. Note over Client,User: Human-in-the-loop review
  7854. Client->>User: Present request for approval
  7855. User-->>Client: Review and approve/modify
  7856. Note over Client,LLM: Model interaction
  7857. Client->>LLM: Forward approved request
  7858. LLM-->>Client: Return generation
  7859. Note over Client,User: Response review
  7860. Client->>User: Present response for approval
  7861. User-->>Client: Review and approve/modify
  7862. Note over Server,Client: Complete request
  7863. Client-->>Server: Return approved response
  7864. ```
  7865. ## Data Types
  7866. ### Messages
  7867. Sampling messages can contain:
  7868. #### Text Content
  7869. ```json
  7870. {
  7871. "type": "text",
  7872. "text": "The message content"
  7873. }
  7874. ```
  7875. #### Image Content
  7876. ```json
  7877. {
  7878. "type": "image",
  7879. "data": "base64-encoded-image-data",
  7880. "mimeType": "image/jpeg"
  7881. }
  7882. ```
  7883. ### Model Preferences
  7884. Model selection in MCP requires careful abstraction since servers and clients may use
  7885. different AI providers with distinct model offerings. A server cannot simply request a
  7886. specific model by name since the client may not have access to that exact model or may
  7887. prefer to use a different provider's equivalent model.
  7888. To solve this, MCP implements a preference system that combines abstract capability
  7889. priorities with optional model hints:
  7890. #### Capability Priorities
  7891. Servers express their needs through three normalized priority values (0-1):
  7892. * `costPriority`: How important is minimizing costs? Higher values prefer cheaper models.
  7893. * `speedPriority`: How important is low latency? Higher values prefer faster models.
  7894. * `intelligencePriority`: How important are advanced capabilities? Higher values prefer
  7895. more capable models.
  7896. #### Model Hints
  7897. While priorities help select models based on characteristics, `hints` allow servers to
  7898. suggest specific models or model families:
  7899. * Hints are treated as substrings that can match model names flexibly
  7900. * Multiple hints are evaluated in order of preference
  7901. * Clients **MAY** map hints to equivalent models from different providers
  7902. * Hints are advisory—clients make final model selection
  7903. For example:
  7904. ```json
  7905. {
  7906. "hints": [
  7907. { "name": "claude-3-sonnet" }, // Prefer Sonnet-class models
  7908. { "name": "claude" } // Fall back to any Claude model
  7909. ],
  7910. "costPriority": 0.3, // Cost is less important
  7911. "speedPriority": 0.8, // Speed is very important
  7912. "intelligencePriority": 0.5 // Moderate capability needs
  7913. }
  7914. ```
  7915. The client processes these preferences to select an appropriate model from its available
  7916. options. For instance, if the client doesn't have access to Claude models but has Gemini,
  7917. it might map the sonnet hint to `gemini-1.5-pro` based on similar capabilities.
  7918. ## Error Handling
  7919. Clients **SHOULD** return errors for common failure cases:
  7920. Example error:
  7921. ```json
  7922. {
  7923. "jsonrpc": "2.0",
  7924. "id": 1,
  7925. "error": {
  7926. "code": -1,
  7927. "message": "User rejected sampling request"
  7928. }
  7929. }
  7930. ```
  7931. ## Security Considerations
  7932. 1. Clients **SHOULD** implement user approval controls
  7933. 2. Both parties **SHOULD** validate message content
  7934. 3. Clients **SHOULD** respect model preference hints
  7935. 4. Clients **SHOULD** implement rate limiting
  7936. 5. Both parties **MUST** handle sensitive data appropriately
  7937. # Specification
  7938. Source: https://modelcontextprotocol.io/specification/2024-11-05/index
  7939. [Model Context Protocol](https://modelcontextprotocol.io) (MCP) is an open protocol that
  7940. enables seamless integration between LLM applications and external data sources and
  7941. tools. Whether you're building an AI-powered IDE, enhancing a chat interface, or creating
  7942. custom AI workflows, MCP provides a standardized way to connect LLMs with the context
  7943. they need.
  7944. This specification defines the authoritative protocol requirements, based on the
  7945. TypeScript schema in
  7946. [schema.ts](https://github.com/modelcontextprotocol/specification/blob/main/schema/2024-11-05/schema.ts).
  7947. For implementation guides and examples, visit
  7948. [modelcontextprotocol.io](https://modelcontextprotocol.io).
  7949. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD
  7950. NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be
  7951. interpreted as described in [BCP 14](https://datatracker.ietf.org/doc/html/bcp14)
  7952. \[[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)]
  7953. \[[RFC8174](https://datatracker.ietf.org/doc/html/rfc8174)] when, and only when, they
  7954. appear in all capitals, as shown here.
  7955. ## Overview
  7956. MCP provides a standardized way for applications to:
  7957. * Share contextual information with language models
  7958. * Expose tools and capabilities to AI systems
  7959. * Build composable integrations and workflows
  7960. The protocol uses [JSON-RPC](https://www.jsonrpc.org/) 2.0 messages to establish
  7961. communication between:
  7962. * **Hosts**: LLM applications that initiate connections
  7963. * **Clients**: Connectors within the host application
  7964. * **Servers**: Services that provide context and capabilities
  7965. MCP takes some inspiration from the
  7966. [Language Server Protocol](https://microsoft.github.io/language-server-protocol/), which
  7967. standardizes how to add support for programming languages across a whole ecosystem of
  7968. development tools. In a similar way, MCP standardizes how to integrate additional context
  7969. and tools into the ecosystem of AI applications.
  7970. ## Key Details
  7971. ### Base Protocol
  7972. * [JSON-RPC](https://www.jsonrpc.org/) message format
  7973. * Stateful connections
  7974. * Server and client capability negotiation
  7975. ### Features
  7976. Servers offer any of the following features to clients:
  7977. * **Resources**: Context and data, for the user or the AI model to use
  7978. * **Prompts**: Templated messages and workflows for users
  7979. * **Tools**: Functions for the AI model to execute
  7980. Clients may offer the following feature to servers:
  7981. * **Sampling**: Server-initiated agentic behaviors and recursive LLM interactions
  7982. ### Additional Utilities
  7983. * Configuration
  7984. * Progress tracking
  7985. * Cancellation
  7986. * Error reporting
  7987. * Logging
  7988. ## Security and Trust & Safety
  7989. The Model Context Protocol enables powerful capabilities through arbitrary data access
  7990. and code execution paths. With this power comes important security and trust
  7991. considerations that all implementors must carefully address.
  7992. ### Key Principles
  7993. 1. **User Consent and Control**
  7994. * Users must explicitly consent to and understand all data access and operations
  7995. * Users must retain control over what data is shared and what actions are taken
  7996. * Implementors should provide clear UIs for reviewing and authorizing activities
  7997. 2. **Data Privacy**
  7998. * Hosts must obtain explicit user consent before exposing user data to servers
  7999. * Hosts must not transmit resource data elsewhere without user consent
  8000. * User data should be protected with appropriate access controls
  8001. 3. **Tool Safety**
  8002. * Tools represent arbitrary code execution and must be treated with appropriate
  8003. caution
  8004. * Hosts must obtain explicit user consent before invoking any tool
  8005. * Users should understand what each tool does before authorizing its use
  8006. 4. **LLM Sampling Controls**
  8007. * Users must explicitly approve any LLM sampling requests
  8008. * Users should control:
  8009. * Whether sampling occurs at all
  8010. * The actual prompt that will be sent
  8011. * What results the server can see
  8012. * The protocol intentionally limits server visibility into prompts
  8013. ### Implementation Guidelines
  8014. While MCP itself cannot enforce these security principles at the protocol level,
  8015. implementors **SHOULD**:
  8016. 1. Build robust consent and authorization flows into their applications
  8017. 2. Provide clear documentation of security implications
  8018. 3. Implement appropriate access controls and data protections
  8019. 4. Follow security best practices in their integrations
  8020. 5. Consider privacy implications in their feature designs
  8021. ## Learn More
  8022. Explore the detailed specification for each protocol component:
  8023. <CardGroup cols={5}>
  8024. <Card title="Architecture" icon="sitemap" href="/specification/2024-11-05/architecture" />
  8025. <Card title="Base Protocol" icon="code" href="/specification/2024-11-05/basic" />
  8026. <Card title="Server Features" icon="server" href="/specification/2024-11-05/server" />
  8027. <Card title="Client Features" icon="user" href="/specification/2024-11-05/client" />
  8028. <Card title="Contributing" icon="pencil" href="/specification/contributing" />
  8029. </CardGroup>
  8030. # Overview
  8031. Source: https://modelcontextprotocol.io/specification/2024-11-05/server/index
  8032. <Info>**Protocol Revision**: 2024-11-05</Info>
  8033. Servers provide the fundamental building blocks for adding context to language models via
  8034. MCP. These primitives enable rich interactions between clients, servers, and language
  8035. models:
  8036. * **Prompts**: Pre-defined templates or instructions that guide language model
  8037. interactions
  8038. * **Resources**: Structured data or content that provides additional context to the model
  8039. * **Tools**: Executable functions that allow models to perform actions or retrieve
  8040. information
  8041. Each primitive can be summarized in the following control hierarchy:
  8042. | Primitive | Control | Description | Example |
  8043. | --------- | ---------------------- | -------------------------------------------------- | ------------------------------- |
  8044. | Prompts | User-controlled | Interactive templates invoked by user choice | Slash commands, menu options |
  8045. | Resources | Application-controlled | Contextual data attached and managed by the client | File contents, git history |
  8046. | Tools | Model-controlled | Functions exposed to the LLM to take actions | API POST requests, file writing |
  8047. Explore these key primitives in more detail below:
  8048. <CardGroup cols={3}>
  8049. <Card title="Prompts" icon="message" href="/specification/2024-11-05/server/prompts" />
  8050. <Card title="Resources" icon="file-lines" href="/specification/2024-11-05/server/resources" />
  8051. <Card title="Tools" icon="wrench" href="/specification/2024-11-05/server/tools" />
  8052. </CardGroup>
  8053. # Prompts
  8054. Source: https://modelcontextprotocol.io/specification/2024-11-05/server/prompts
  8055. <Info>**Protocol Revision**: 2024-11-05</Info>
  8056. The Model Context Protocol (MCP) provides a standardized way for servers to expose prompt
  8057. templates to clients. Prompts allow servers to provide structured messages and
  8058. instructions for interacting with language models. Clients can discover available
  8059. prompts, retrieve their contents, and provide arguments to customize them.
  8060. ## User Interaction Model
  8061. Prompts are designed to be **user-controlled**, meaning they are exposed from servers to
  8062. clients with the intention of the user being able to explicitly select them for use.
  8063. Typically, prompts would be triggered through user-initiated commands in the user
  8064. interface, which allows users to naturally discover and invoke available prompts.
  8065. For example, as slash commands:
  8066. ![Example of prompt exposed as slash command](https://mintlify.s3.us-west-1.amazonaws.com/mcp/specification/2024-11-05/server/slash-command.png)
  8067. However, implementors are free to expose prompts through any interface pattern that suits
  8068. their needs—the protocol itself does not mandate any specific user interaction
  8069. model.
  8070. ## Capabilities
  8071. Servers that support prompts **MUST** declare the `prompts` capability during
  8072. [initialization](/specification/2024-11-05/basic/lifecycle#initialization):
  8073. ```json
  8074. {
  8075. "capabilities": {
  8076. "prompts": {
  8077. "listChanged": true
  8078. }
  8079. }
  8080. }
  8081. ```
  8082. `listChanged` indicates whether the server will emit notifications when the list of
  8083. available prompts changes.
  8084. ## Protocol Messages
  8085. ### Listing Prompts
  8086. To retrieve available prompts, clients send a `prompts/list` request. This operation
  8087. supports
  8088. [pagination](/specification/2024-11-05/server/utilities/pagination).
  8089. **Request:**
  8090. ```json
  8091. {
  8092. "jsonrpc": "2.0",
  8093. "id": 1,
  8094. "method": "prompts/list",
  8095. "params": {
  8096. "cursor": "optional-cursor-value"
  8097. }
  8098. }
  8099. ```
  8100. **Response:**
  8101. ```json
  8102. {
  8103. "jsonrpc": "2.0",
  8104. "id": 1,
  8105. "result": {
  8106. "prompts": [
  8107. {
  8108. "name": "code_review",
  8109. "description": "Asks the LLM to analyze code quality and suggest improvements",
  8110. "arguments": [
  8111. {
  8112. "name": "code",
  8113. "description": "The code to review",
  8114. "required": true
  8115. }
  8116. ]
  8117. }
  8118. ],
  8119. "nextCursor": "next-page-cursor"
  8120. }
  8121. }
  8122. ```
  8123. ### Getting a Prompt
  8124. To retrieve a specific prompt, clients send a `prompts/get` request. Arguments may be
  8125. auto-completed through [the completion API](/specification/2024-11-05/server/utilities/completion).
  8126. **Request:**
  8127. ```json
  8128. {
  8129. "jsonrpc": "2.0",
  8130. "id": 2,
  8131. "method": "prompts/get",
  8132. "params": {
  8133. "name": "code_review",
  8134. "arguments": {
  8135. "code": "def hello():\n print('world')"
  8136. }
  8137. }
  8138. }
  8139. ```
  8140. **Response:**
  8141. ```json
  8142. {
  8143. "jsonrpc": "2.0",
  8144. "id": 2,
  8145. "result": {
  8146. "description": "Code review prompt",
  8147. "messages": [
  8148. {
  8149. "role": "user",
  8150. "content": {
  8151. "type": "text",
  8152. "text": "Please review this Python code:\ndef hello():\n print('world')"
  8153. }
  8154. }
  8155. ]
  8156. }
  8157. }
  8158. ```
  8159. ### List Changed Notification
  8160. When the list of available prompts changes, servers that declared the `listChanged`
  8161. capability **SHOULD** send a notification:
  8162. ```json
  8163. {
  8164. "jsonrpc": "2.0",
  8165. "method": "notifications/prompts/list_changed"
  8166. }
  8167. ```
  8168. ## Message Flow
  8169. ```mermaid
  8170. sequenceDiagram
  8171. participant Client
  8172. participant Server
  8173. Note over Client,Server: Discovery
  8174. Client->>Server: prompts/list
  8175. Server-->>Client: List of prompts
  8176. Note over Client,Server: Usage
  8177. Client->>Server: prompts/get
  8178. Server-->>Client: Prompt content
  8179. opt listChanged
  8180. Note over Client,Server: Changes
  8181. Server--)Client: prompts/list_changed
  8182. Client->>Server: prompts/list
  8183. Server-->>Client: Updated prompts
  8184. end
  8185. ```
  8186. ## Data Types
  8187. ### Prompt
  8188. A prompt definition includes:
  8189. * `name`: Unique identifier for the prompt
  8190. * `description`: Optional human-readable description
  8191. * `arguments`: Optional list of arguments for customization
  8192. ### PromptMessage
  8193. Messages in a prompt can contain:
  8194. * `role`: Either "user" or "assistant" to indicate the speaker
  8195. * `content`: One of the following content types:
  8196. #### Text Content
  8197. Text content represents plain text messages:
  8198. ```json
  8199. {
  8200. "type": "text",
  8201. "text": "The text content of the message"
  8202. }
  8203. ```
  8204. This is the most common content type used for natural language interactions.
  8205. #### Image Content
  8206. Image content allows including visual information in messages:
  8207. ```json
  8208. {
  8209. "type": "image",
  8210. "data": "base64-encoded-image-data",
  8211. "mimeType": "image/png"
  8212. }
  8213. ```
  8214. The image data **MUST** be base64-encoded and include a valid MIME type. This enables
  8215. multi-modal interactions where visual context is important.
  8216. #### Embedded Resources
  8217. Embedded resources allow referencing server-side resources directly in messages:
  8218. ```json
  8219. {
  8220. "type": "resource",
  8221. "resource": {
  8222. "uri": "resource://example",
  8223. "mimeType": "text/plain",
  8224. "text": "Resource content"
  8225. }
  8226. }
  8227. ```
  8228. Resources can contain either text or binary (blob) data and **MUST** include:
  8229. * A valid resource URI
  8230. * The appropriate MIME type
  8231. * Either text content or base64-encoded blob data
  8232. Embedded resources enable prompts to seamlessly incorporate server-managed content like
  8233. documentation, code samples, or other reference materials directly into the conversation
  8234. flow.
  8235. ## Error Handling
  8236. Servers **SHOULD** return standard JSON-RPC errors for common failure cases:
  8237. * Invalid prompt name: `-32602` (Invalid params)
  8238. * Missing required arguments: `-32602` (Invalid params)
  8239. * Internal errors: `-32603` (Internal error)
  8240. ## Implementation Considerations
  8241. 1. Servers **SHOULD** validate prompt arguments before processing
  8242. 2. Clients **SHOULD** handle pagination for large prompt lists
  8243. 3. Both parties **SHOULD** respect capability negotiation
  8244. ## Security
  8245. Implementations **MUST** carefully validate all prompt inputs and outputs to prevent
  8246. injection attacks or unauthorized access to resources.
  8247. # Resources
  8248. Source: https://modelcontextprotocol.io/specification/2024-11-05/server/resources
  8249. <Info>**Protocol Revision**: 2024-11-05</Info>
  8250. The Model Context Protocol (MCP) provides a standardized way for servers to expose
  8251. resources to clients. Resources allow servers to share data that provides context to
  8252. language models, such as files, database schemas, or application-specific information.
  8253. Each resource is uniquely identified by a
  8254. [URI](https://datatracker.ietf.org/doc/html/rfc3986).
  8255. ## User Interaction Model
  8256. Resources in MCP are designed to be **application-driven**, with host applications
  8257. determining how to incorporate context based on their needs.
  8258. For example, applications could:
  8259. * Expose resources through UI elements for explicit selection, in a tree or list view
  8260. * Allow the user to search through and filter available resources
  8261. * Implement automatic context inclusion, based on heuristics or the AI model's selection
  8262. ![Example of resource context picker](https://mintlify.s3.us-west-1.amazonaws.com/mcp/specification/2024-11-05/server/resource-picker.png)
  8263. However, implementations are free to expose resources through any interface pattern that
  8264. suits their needs—the protocol itself does not mandate any specific user
  8265. interaction model.
  8266. ## Capabilities
  8267. Servers that support resources **MUST** declare the `resources` capability:
  8268. ```json
  8269. {
  8270. "capabilities": {
  8271. "resources": {
  8272. "subscribe": true,
  8273. "listChanged": true
  8274. }
  8275. }
  8276. }
  8277. ```
  8278. The capability supports two optional features:
  8279. * `subscribe`: whether the client can subscribe to be notified of changes to individual
  8280. resources.
  8281. * `listChanged`: whether the server will emit notifications when the list of available
  8282. resources changes.
  8283. Both `subscribe` and `listChanged` are optional—servers can support neither,
  8284. either, or both:
  8285. ```json
  8286. {
  8287. "capabilities": {
  8288. "resources": {} // Neither feature supported
  8289. }
  8290. }
  8291. ```
  8292. ```json
  8293. {
  8294. "capabilities": {
  8295. "resources": {
  8296. "subscribe": true // Only subscriptions supported
  8297. }
  8298. }
  8299. }
  8300. ```
  8301. ```json
  8302. {
  8303. "capabilities": {
  8304. "resources": {
  8305. "listChanged": true // Only list change notifications supported
  8306. }
  8307. }
  8308. }
  8309. ```
  8310. ## Protocol Messages
  8311. ### Listing Resources
  8312. To discover available resources, clients send a `resources/list` request. This operation
  8313. supports
  8314. [pagination](/specification/2024-11-05/server/utilities/pagination).
  8315. **Request:**
  8316. ```json
  8317. {
  8318. "jsonrpc": "2.0",
  8319. "id": 1,
  8320. "method": "resources/list",
  8321. "params": {
  8322. "cursor": "optional-cursor-value"
  8323. }
  8324. }
  8325. ```
  8326. **Response:**
  8327. ```json
  8328. {
  8329. "jsonrpc": "2.0",
  8330. "id": 1,
  8331. "result": {
  8332. "resources": [
  8333. {
  8334. "uri": "file:///project/src/main.rs",
  8335. "name": "main.rs",
  8336. "description": "Primary application entry point",
  8337. "mimeType": "text/x-rust"
  8338. }
  8339. ],
  8340. "nextCursor": "next-page-cursor"
  8341. }
  8342. }
  8343. ```
  8344. ### Reading Resources
  8345. To retrieve resource contents, clients send a `resources/read` request:
  8346. **Request:**
  8347. ```json
  8348. {
  8349. "jsonrpc": "2.0",
  8350. "id": 2,
  8351. "method": "resources/read",
  8352. "params": {
  8353. "uri": "file:///project/src/main.rs"
  8354. }
  8355. }
  8356. ```
  8357. **Response:**
  8358. ```json
  8359. {
  8360. "jsonrpc": "2.0",
  8361. "id": 2,
  8362. "result": {
  8363. "contents": [
  8364. {
  8365. "uri": "file:///project/src/main.rs",
  8366. "mimeType": "text/x-rust",
  8367. "text": "fn main() {\n println!(\"Hello world!\");\n}"
  8368. }
  8369. ]
  8370. }
  8371. }
  8372. ```
  8373. ### Resource Templates
  8374. Resource templates allow servers to expose parameterized resources using
  8375. [URI templates](https://datatracker.ietf.org/doc/html/rfc6570). Arguments may be
  8376. auto-completed through [the completion API](/specification/2024-11-05/server/utilities/completion).
  8377. **Request:**
  8378. ```json
  8379. {
  8380. "jsonrpc": "2.0",
  8381. "id": 3,
  8382. "method": "resources/templates/list"
  8383. }
  8384. ```
  8385. **Response:**
  8386. ```json
  8387. {
  8388. "jsonrpc": "2.0",
  8389. "id": 3,
  8390. "result": {
  8391. "resourceTemplates": [
  8392. {
  8393. "uriTemplate": "file:///{path}",
  8394. "name": "Project Files",
  8395. "description": "Access files in the project directory",
  8396. "mimeType": "application/octet-stream"
  8397. }
  8398. ]
  8399. }
  8400. }
  8401. ```
  8402. ### List Changed Notification
  8403. When the list of available resources changes, servers that declared the `listChanged`
  8404. capability **SHOULD** send a notification:
  8405. ```json
  8406. {
  8407. "jsonrpc": "2.0",
  8408. "method": "notifications/resources/list_changed"
  8409. }
  8410. ```
  8411. ### Subscriptions
  8412. The protocol supports optional subscriptions to resource changes. Clients can subscribe
  8413. to specific resources and receive notifications when they change:
  8414. **Subscribe Request:**
  8415. ```json
  8416. {
  8417. "jsonrpc": "2.0",
  8418. "id": 4,
  8419. "method": "resources/subscribe",
  8420. "params": {
  8421. "uri": "file:///project/src/main.rs"
  8422. }
  8423. }
  8424. ```
  8425. **Update Notification:**
  8426. ```json
  8427. {
  8428. "jsonrpc": "2.0",
  8429. "method": "notifications/resources/updated",
  8430. "params": {
  8431. "uri": "file:///project/src/main.rs"
  8432. }
  8433. }
  8434. ```
  8435. ## Message Flow
  8436. ```mermaid
  8437. sequenceDiagram
  8438. participant Client
  8439. participant Server
  8440. Note over Client,Server: Resource Discovery
  8441. Client->>Server: resources/list
  8442. Server-->>Client: List of resources
  8443. Note over Client,Server: Resource Access
  8444. Client->>Server: resources/read
  8445. Server-->>Client: Resource contents
  8446. Note over Client,Server: Subscriptions
  8447. Client->>Server: resources/subscribe
  8448. Server-->>Client: Subscription confirmed
  8449. Note over Client,Server: Updates
  8450. Server--)Client: notifications/resources/updated
  8451. Client->>Server: resources/read
  8452. Server-->>Client: Updated contents
  8453. ```
  8454. ## Data Types
  8455. ### Resource
  8456. A resource definition includes:
  8457. * `uri`: Unique identifier for the resource
  8458. * `name`: Human-readable name
  8459. * `description`: Optional description
  8460. * `mimeType`: Optional MIME type
  8461. ### Resource Contents
  8462. Resources can contain either text or binary data:
  8463. #### Text Content
  8464. ```json
  8465. {
  8466. "uri": "file:///example.txt",
  8467. "mimeType": "text/plain",
  8468. "text": "Resource content"
  8469. }
  8470. ```
  8471. #### Binary Content
  8472. ```json
  8473. {
  8474. "uri": "file:///example.png",
  8475. "mimeType": "image/png",
  8476. "blob": "base64-encoded-data"
  8477. }
  8478. ```
  8479. ## Common URI Schemes
  8480. The protocol defines several standard URI schemes. This list not
  8481. exhaustive—implementations are always free to use additional, custom URI schemes.
  8482. ### https\://
  8483. Used to represent a resource available on the web.
  8484. Servers **SHOULD** use this scheme only when the client is able to fetch and load the
  8485. resource directly from the web on its own—that is, it doesn’t need to read the resource
  8486. via the MCP server.
  8487. For other use cases, servers **SHOULD** prefer to use another URI scheme, or define a
  8488. custom one, even if the server will itself be downloading resource contents over the
  8489. internet.
  8490. ### file://
  8491. Used to identify resources that behave like a filesystem. However, the resources do not
  8492. need to map to an actual physical filesystem.
  8493. MCP servers **MAY** identify file:// resources with an
  8494. [XDG MIME type](https://specifications.freedesktop.org/shared-mime-info-spec/0.14/ar01s02.html#id-1.3.14),
  8495. like `inode/directory`, to represent non-regular files (such as directories) that don’t
  8496. otherwise have a standard MIME type.
  8497. ### git://
  8498. Git version control integration.
  8499. ## Error Handling
  8500. Servers **SHOULD** return standard JSON-RPC errors for common failure cases:
  8501. * Resource not found: `-32002`
  8502. * Internal errors: `-32603`
  8503. Example error:
  8504. ```json
  8505. {
  8506. "jsonrpc": "2.0",
  8507. "id": 5,
  8508. "error": {
  8509. "code": -32002,
  8510. "message": "Resource not found",
  8511. "data": {
  8512. "uri": "file:///nonexistent.txt"
  8513. }
  8514. }
  8515. }
  8516. ```
  8517. ## Security Considerations
  8518. 1. Servers **MUST** validate all resource URIs
  8519. 2. Access controls **SHOULD** be implemented for sensitive resources
  8520. 3. Binary data **MUST** be properly encoded
  8521. 4. Resource permissions **SHOULD** be checked before operations
  8522. # Tools
  8523. Source: https://modelcontextprotocol.io/specification/2024-11-05/server/tools
  8524. <Info>**Protocol Revision**: 2024-11-05</Info>
  8525. The Model Context Protocol (MCP) allows servers to expose tools that can be invoked by
  8526. language models. Tools enable models to interact with external systems, such as querying
  8527. databases, calling APIs, or performing computations. Each tool is uniquely identified by
  8528. a name and includes metadata describing its schema.
  8529. ## User Interaction Model
  8530. Tools in MCP are designed to be **model-controlled**, meaning that the language model can
  8531. discover and invoke tools automatically based on its contextual understanding and the
  8532. user's prompts.
  8533. However, implementations are free to expose tools through any interface pattern that
  8534. suits their needs—the protocol itself does not mandate any specific user
  8535. interaction model.
  8536. <Warning>
  8537. For trust & safety and security, there **SHOULD** always
  8538. be a human in the loop with the ability to deny tool invocations.
  8539. Applications **SHOULD**:
  8540. * Provide UI that makes clear which tools are being exposed to the AI model
  8541. * Insert clear visual indicators when tools are invoked
  8542. * Present confirmation prompts to the user for operations, to ensure a human is in the
  8543. loop
  8544. </Warning>
  8545. ## Capabilities
  8546. Servers that support tools **MUST** declare the `tools` capability:
  8547. ```json
  8548. {
  8549. "capabilities": {
  8550. "tools": {
  8551. "listChanged": true
  8552. }
  8553. }
  8554. }
  8555. ```
  8556. `listChanged` indicates whether the server will emit notifications when the list of
  8557. available tools changes.
  8558. ## Protocol Messages
  8559. ### Listing Tools
  8560. To discover available tools, clients send a `tools/list` request. This operation supports
  8561. [pagination](/specification/2024-11-05/server/utilities/pagination).
  8562. **Request:**
  8563. ```json
  8564. {
  8565. "jsonrpc": "2.0",
  8566. "id": 1,
  8567. "method": "tools/list",
  8568. "params": {
  8569. "cursor": "optional-cursor-value"
  8570. }
  8571. }
  8572. ```
  8573. **Response:**
  8574. ```json
  8575. {
  8576. "jsonrpc": "2.0",
  8577. "id": 1,
  8578. "result": {
  8579. "tools": [
  8580. {
  8581. "name": "get_weather",
  8582. "description": "Get current weather information for a location",
  8583. "inputSchema": {
  8584. "type": "object",
  8585. "properties": {
  8586. "location": {
  8587. "type": "string",
  8588. "description": "City name or zip code"
  8589. }
  8590. },
  8591. "required": ["location"]
  8592. }
  8593. }
  8594. ],
  8595. "nextCursor": "next-page-cursor"
  8596. }
  8597. }
  8598. ```
  8599. ### Calling Tools
  8600. To invoke a tool, clients send a `tools/call` request:
  8601. **Request:**
  8602. ```json
  8603. {
  8604. "jsonrpc": "2.0",
  8605. "id": 2,
  8606. "method": "tools/call",
  8607. "params": {
  8608. "name": "get_weather",
  8609. "arguments": {
  8610. "location": "New York"
  8611. }
  8612. }
  8613. }
  8614. ```
  8615. **Response:**
  8616. ```json
  8617. {
  8618. "jsonrpc": "2.0",
  8619. "id": 2,
  8620. "result": {
  8621. "content": [
  8622. {
  8623. "type": "text",
  8624. "text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy"
  8625. }
  8626. ],
  8627. "isError": false
  8628. }
  8629. }
  8630. ```
  8631. ### List Changed Notification
  8632. When the list of available tools changes, servers that declared the `listChanged`
  8633. capability **SHOULD** send a notification:
  8634. ```json
  8635. {
  8636. "jsonrpc": "2.0",
  8637. "method": "notifications/tools/list_changed"
  8638. }
  8639. ```
  8640. ## Message Flow
  8641. ```mermaid
  8642. sequenceDiagram
  8643. participant LLM
  8644. participant Client
  8645. participant Server
  8646. Note over Client,Server: Discovery
  8647. Client->>Server: tools/list
  8648. Server-->>Client: List of tools
  8649. Note over Client,LLM: Tool Selection
  8650. LLM->>Client: Select tool to use
  8651. Note over Client,Server: Invocation
  8652. Client->>Server: tools/call
  8653. Server-->>Client: Tool result
  8654. Client->>LLM: Process result
  8655. Note over Client,Server: Updates
  8656. Server--)Client: tools/list_changed
  8657. Client->>Server: tools/list
  8658. Server-->>Client: Updated tools
  8659. ```
  8660. ## Data Types
  8661. ### Tool
  8662. A tool definition includes:
  8663. * `name`: Unique identifier for the tool
  8664. * `description`: Human-readable description of functionality
  8665. * `inputSchema`: JSON Schema defining expected parameters
  8666. ### Tool Result
  8667. Tool results can contain multiple content items of different types:
  8668. #### Text Content
  8669. ```json
  8670. {
  8671. "type": "text",
  8672. "text": "Tool result text"
  8673. }
  8674. ```
  8675. #### Image Content
  8676. ```json
  8677. {
  8678. "type": "image",
  8679. "data": "base64-encoded-data",
  8680. "mimeType": "image/png"
  8681. }
  8682. ```
  8683. #### Embedded Resources
  8684. [Resources](/specification/2024-11-05/server/resources) **MAY** be
  8685. embedded, to provide additional context or data, behind a URI that can be subscribed to
  8686. or fetched again by the client later:
  8687. ```json
  8688. {
  8689. "type": "resource",
  8690. "resource": {
  8691. "uri": "resource://example",
  8692. "mimeType": "text/plain",
  8693. "text": "Resource content"
  8694. }
  8695. }
  8696. ```
  8697. ## Error Handling
  8698. Tools use two error reporting mechanisms:
  8699. 1. **Protocol Errors**: Standard JSON-RPC errors for issues like:
  8700. * Unknown tools
  8701. * Invalid arguments
  8702. * Server errors
  8703. 2. **Tool Execution Errors**: Reported in tool results with `isError: true`:
  8704. * API failures
  8705. * Invalid input data
  8706. * Business logic errors
  8707. Example protocol error:
  8708. ```json
  8709. {
  8710. "jsonrpc": "2.0",
  8711. "id": 3,
  8712. "error": {
  8713. "code": -32602,
  8714. "message": "Unknown tool: invalid_tool_name"
  8715. }
  8716. }
  8717. ```
  8718. Example tool execution error:
  8719. ```json
  8720. {
  8721. "jsonrpc": "2.0",
  8722. "id": 4,
  8723. "result": {
  8724. "content": [
  8725. {
  8726. "type": "text",
  8727. "text": "Failed to fetch weather data: API rate limit exceeded"
  8728. }
  8729. ],
  8730. "isError": true
  8731. }
  8732. }
  8733. ```
  8734. ## Security Considerations
  8735. 1. Servers **MUST**:
  8736. * Validate all tool inputs
  8737. * Implement proper access controls
  8738. * Rate limit tool invocations
  8739. * Sanitize tool outputs
  8740. 2. Clients **SHOULD**:
  8741. * Prompt for user confirmation on sensitive operations
  8742. * Show tool inputs to the user before calling the server, to avoid malicious or
  8743. accidental data exfiltration
  8744. * Validate tool results before passing to LLM
  8745. * Implement timeouts for tool calls
  8746. * Log tool usage for audit purposes
  8747. # Completion
  8748. Source: https://modelcontextprotocol.io/specification/2024-11-05/server/utilities/completion
  8749. <Info>**Protocol Revision**: 2024-11-05</Info>
  8750. The Model Context Protocol (MCP) provides a standardized way for servers to offer
  8751. argument autocompletion suggestions for prompts and resource URIs. This enables rich,
  8752. IDE-like experiences where users receive contextual suggestions while entering argument
  8753. values.
  8754. ## User Interaction Model
  8755. Completion in MCP is designed to support interactive user experiences similar to IDE code
  8756. completion.
  8757. For example, applications may show completion suggestions in a dropdown or popup menu as
  8758. users type, with the ability to filter and select from available options.
  8759. However, implementations are free to expose completion through any interface pattern that
  8760. suits their needs—the protocol itself does not mandate any specific user
  8761. interaction model.
  8762. ## Protocol Messages
  8763. ### Requesting Completions
  8764. To get completion suggestions, clients send a `completion/complete` request specifying
  8765. what is being completed through a reference type:
  8766. **Request:**
  8767. ```json
  8768. {
  8769. "jsonrpc": "2.0",
  8770. "id": 1,
  8771. "method": "completion/complete",
  8772. "params": {
  8773. "ref": {
  8774. "type": "ref/prompt",
  8775. "name": "code_review"
  8776. },
  8777. "argument": {
  8778. "name": "language",
  8779. "value": "py"
  8780. }
  8781. }
  8782. }
  8783. ```
  8784. **Response:**
  8785. ```json
  8786. {
  8787. "jsonrpc": "2.0",
  8788. "id": 1,
  8789. "result": {
  8790. "completion": {
  8791. "values": ["python", "pytorch", "pyside"],
  8792. "total": 10,
  8793. "hasMore": true
  8794. }
  8795. }
  8796. }
  8797. ```
  8798. ### Reference Types
  8799. The protocol supports two types of completion references:
  8800. | Type | Description | Example |
  8801. | -------------- | --------------------------- | --------------------------------------------------- |
  8802. | `ref/prompt` | References a prompt by name | `{"type": "ref/prompt", "name": "code_review"}` |
  8803. | `ref/resource` | References a resource URI | `{"type": "ref/resource", "uri": "file:///{path}"}` |
  8804. ### Completion Results
  8805. Servers return an array of completion values ranked by relevance, with:
  8806. * Maximum 100 items per response
  8807. * Optional total number of available matches
  8808. * Boolean indicating if additional results exist
  8809. ## Message Flow
  8810. ```mermaid
  8811. sequenceDiagram
  8812. participant Client
  8813. participant Server
  8814. Note over Client: User types argument
  8815. Client->>Server: completion/complete
  8816. Server-->>Client: Completion suggestions
  8817. Note over Client: User continues typing
  8818. Client->>Server: completion/complete
  8819. Server-->>Client: Refined suggestions
  8820. ```
  8821. ## Data Types
  8822. ### CompleteRequest
  8823. * `ref`: A `PromptReference` or `ResourceReference`
  8824. * `argument`: Object containing:
  8825. * `name`: Argument name
  8826. * `value`: Current value
  8827. ### CompleteResult
  8828. * `completion`: Object containing:
  8829. * `values`: Array of suggestions (max 100)
  8830. * `total`: Optional total matches
  8831. * `hasMore`: Additional results flag
  8832. ## Implementation Considerations
  8833. 1. Servers **SHOULD**:
  8834. * Return suggestions sorted by relevance
  8835. * Implement fuzzy matching where appropriate
  8836. * Rate limit completion requests
  8837. * Validate all inputs
  8838. 2. Clients **SHOULD**:
  8839. * Debounce rapid completion requests
  8840. * Cache completion results where appropriate
  8841. * Handle missing or partial results gracefully
  8842. ## Security
  8843. Implementations **MUST**:
  8844. * Validate all completion inputs
  8845. * Implement appropriate rate limiting
  8846. * Control access to sensitive suggestions
  8847. * Prevent completion-based information disclosure
  8848. # Logging
  8849. Source: https://modelcontextprotocol.io/specification/2024-11-05/server/utilities/logging
  8850. <Info>**Protocol Revision**: 2024-11-05</Info>
  8851. The Model Context Protocol (MCP) provides a standardized way for servers to send
  8852. structured log messages to clients. Clients can control logging verbosity by setting
  8853. minimum log levels, with servers sending notifications containing severity levels,
  8854. optional logger names, and arbitrary JSON-serializable data.
  8855. ## User Interaction Model
  8856. Implementations are free to expose logging through any interface pattern that suits their
  8857. needs—the protocol itself does not mandate any specific user interaction model.
  8858. ## Capabilities
  8859. Servers that emit log message notifications **MUST** declare the `logging` capability:
  8860. ```json
  8861. {
  8862. "capabilities": {
  8863. "logging": {}
  8864. }
  8865. }
  8866. ```
  8867. ## Log Levels
  8868. The protocol follows the standard syslog severity levels specified in
  8869. [RFC 5424](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1):
  8870. | Level | Description | Example Use Case |
  8871. | --------- | -------------------------------- | -------------------------- |
  8872. | debug | Detailed debugging information | Function entry/exit points |
  8873. | info | General informational messages | Operation progress updates |
  8874. | notice | Normal but significant events | Configuration changes |
  8875. | warning | Warning conditions | Deprecated feature usage |
  8876. | error | Error conditions | Operation failures |
  8877. | critical | Critical conditions | System component failures |
  8878. | alert | Action must be taken immediately | Data corruption detected |
  8879. | emergency | System is unusable | Complete system failure |
  8880. ## Protocol Messages
  8881. ### Setting Log Level
  8882. To configure the minimum log level, clients **MAY** send a `logging/setLevel` request:
  8883. **Request:**
  8884. ```json
  8885. {
  8886. "jsonrpc": "2.0",
  8887. "id": 1,
  8888. "method": "logging/setLevel",
  8889. "params": {
  8890. "level": "info"
  8891. }
  8892. }
  8893. ```
  8894. ### Log Message Notifications
  8895. Servers send log messages using `notifications/message` notifications:
  8896. ```json
  8897. {
  8898. "jsonrpc": "2.0",
  8899. "method": "notifications/message",
  8900. "params": {
  8901. "level": "error",
  8902. "logger": "database",
  8903. "data": {
  8904. "error": "Connection failed",
  8905. "details": {
  8906. "host": "localhost",
  8907. "port": 5432
  8908. }
  8909. }
  8910. }
  8911. }
  8912. ```
  8913. ## Message Flow
  8914. ```mermaid
  8915. sequenceDiagram
  8916. participant Client
  8917. participant Server
  8918. Note over Client,Server: Configure Logging
  8919. Client->>Server: logging/setLevel (info)
  8920. Server-->>Client: Empty Result
  8921. Note over Client,Server: Server Activity
  8922. Server--)Client: notifications/message (info)
  8923. Server--)Client: notifications/message (warning)
  8924. Server--)Client: notifications/message (error)
  8925. Note over Client,Server: Level Change
  8926. Client->>Server: logging/setLevel (error)
  8927. Server-->>Client: Empty Result
  8928. Note over Server: Only sends error level<br/>and above
  8929. ```
  8930. ## Error Handling
  8931. Servers **SHOULD** return standard JSON-RPC errors for common failure cases:
  8932. * Invalid log level: `-32602` (Invalid params)
  8933. * Configuration errors: `-32603` (Internal error)
  8934. ## Implementation Considerations
  8935. 1. Servers **SHOULD**:
  8936. * Rate limit log messages
  8937. * Include relevant context in data field
  8938. * Use consistent logger names
  8939. * Remove sensitive information
  8940. 2. Clients **MAY**:
  8941. * Present log messages in the UI
  8942. * Implement log filtering/search
  8943. * Display severity visually
  8944. * Persist log messages
  8945. ## Security
  8946. 1. Log messages **MUST NOT** contain:
  8947. * Credentials or secrets
  8948. * Personal identifying information
  8949. * Internal system details that could aid attacks
  8950. 2. Implementations **SHOULD**:
  8951. * Rate limit messages
  8952. * Validate all data fields
  8953. * Control log access
  8954. * Monitor for sensitive content
  8955. # Pagination
  8956. Source: https://modelcontextprotocol.io/specification/2024-11-05/server/utilities/pagination
  8957. <Info>**Protocol Revision**: 2024-11-05</Info>
  8958. The Model Context Protocol (MCP) supports paginating list operations that may return
  8959. large result sets. Pagination allows servers to yield results in smaller chunks rather
  8960. than all at once.
  8961. Pagination is especially important when connecting to external services over the
  8962. internet, but also useful for local integrations to avoid performance issues with large
  8963. data sets.
  8964. ## Pagination Model
  8965. Pagination in MCP uses an opaque cursor-based approach, instead of numbered pages.
  8966. * The **cursor** is an opaque string token, representing a position in the result set
  8967. * **Page size** is determined by the server, and clients **MUST NOT** assume a fixed page
  8968. size
  8969. ## Response Format
  8970. Pagination starts when the server sends a **response** that includes:
  8971. * The current page of results
  8972. * An optional `nextCursor` field if more results exist
  8973. ```json
  8974. {
  8975. "jsonrpc": "2.0",
  8976. "id": "123",
  8977. "result": {
  8978. "resources": [...],
  8979. "nextCursor": "eyJwYWdlIjogM30="
  8980. }
  8981. }
  8982. ```
  8983. ## Request Format
  8984. After receiving a cursor, the client can *continue* paginating by issuing a request
  8985. including that cursor:
  8986. ```json
  8987. {
  8988. "jsonrpc": "2.0",
  8989. "method": "resources/list",
  8990. "params": {
  8991. "cursor": "eyJwYWdlIjogMn0="
  8992. }
  8993. }
  8994. ```
  8995. ## Pagination Flow
  8996. ```mermaid
  8997. sequenceDiagram
  8998. participant Client
  8999. participant Server
  9000. Client->>Server: List Request (no cursor)
  9001. loop Pagination Loop
  9002. Server-->>Client: Page of results + nextCursor
  9003. Client->>Server: List Request (with cursor)
  9004. end
  9005. ```
  9006. ## Operations Supporting Pagination
  9007. The following MCP operations support pagination:
  9008. * `resources/list` - List available resources
  9009. * `resources/templates/list` - List resource templates
  9010. * `prompts/list` - List available prompts
  9011. * `tools/list` - List available tools
  9012. ## Implementation Guidelines
  9013. 1. Servers **SHOULD**:
  9014. * Provide stable cursors
  9015. * Handle invalid cursors gracefully
  9016. 2. Clients **SHOULD**:
  9017. * Treat a missing `nextCursor` as the end of results
  9018. * Support both paginated and non-paginated flows
  9019. 3. Clients **MUST** treat cursors as opaque tokens:
  9020. * Don't make assumptions about cursor format
  9021. * Don't attempt to parse or modify cursors
  9022. * Don't persist cursors across sessions
  9023. ## Error Handling
  9024. Invalid cursors **SHOULD** result in an error with code -32602 (Invalid params).
  9025. # Architecture
  9026. Source: https://modelcontextprotocol.io/specification/2025-03-26/architecture/index
  9027. The Model Context Protocol (MCP) follows a client-host-server architecture where each
  9028. host can run multiple client instances. This architecture enables users to integrate AI
  9029. capabilities across applications while maintaining clear security boundaries and
  9030. isolating concerns. Built on JSON-RPC, MCP provides a stateful session protocol focused
  9031. on context exchange and sampling coordination between clients and servers.
  9032. ## Core Components
  9033. ```mermaid
  9034. graph LR
  9035. subgraph "Application Host Process"
  9036. H[Host]
  9037. C1[Client 1]
  9038. C2[Client 2]
  9039. C3[Client 3]
  9040. H --> C1
  9041. H --> C2
  9042. H --> C3
  9043. end
  9044. subgraph "Local machine"
  9045. S1[Server 1<br>Files & Git]
  9046. S2[Server 2<br>Database]
  9047. R1[("Local<br>Resource A")]
  9048. R2[("Local<br>Resource B")]
  9049. C1 --> S1
  9050. C2 --> S2
  9051. S1 <--> R1
  9052. S2 <--> R2
  9053. end
  9054. subgraph "Internet"
  9055. S3[Server 3<br>External APIs]
  9056. R3[("Remote<br>Resource C")]
  9057. C3 --> S3
  9058. S3 <--> R3
  9059. end
  9060. ```
  9061. ### Host
  9062. The host process acts as the container and coordinator:
  9063. * Creates and manages multiple client instances
  9064. * Controls client connection permissions and lifecycle
  9065. * Enforces security policies and consent requirements
  9066. * Handles user authorization decisions
  9067. * Coordinates AI/LLM integration and sampling
  9068. * Manages context aggregation across clients
  9069. ### Clients
  9070. Each client is created by the host and maintains an isolated server connection:
  9071. * Establishes one stateful session per server
  9072. * Handles protocol negotiation and capability exchange
  9073. * Routes protocol messages bidirectionally
  9074. * Manages subscriptions and notifications
  9075. * Maintains security boundaries between servers
  9076. A host application creates and manages multiple clients, with each client having a 1:1
  9077. relationship with a particular server.
  9078. ### Servers
  9079. Servers provide specialized context and capabilities:
  9080. * Expose resources, tools and prompts via MCP primitives
  9081. * Operate independently with focused responsibilities
  9082. * Request sampling through client interfaces
  9083. * Must respect security constraints
  9084. * Can be local processes or remote services
  9085. ## Design Principles
  9086. MCP is built on several key design principles that inform its architecture and
  9087. implementation:
  9088. 1. **Servers should be extremely easy to build**
  9089. * Host applications handle complex orchestration responsibilities
  9090. * Servers focus on specific, well-defined capabilities
  9091. * Simple interfaces minimize implementation overhead
  9092. * Clear separation enables maintainable code
  9093. 2. **Servers should be highly composable**
  9094. * Each server provides focused functionality in isolation
  9095. * Multiple servers can be combined seamlessly
  9096. * Shared protocol enables interoperability
  9097. * Modular design supports extensibility
  9098. 3. **Servers should not be able to read the whole conversation, nor "see into" other
  9099. servers**
  9100. * Servers receive only necessary contextual information
  9101. * Full conversation history stays with the host
  9102. * Each server connection maintains isolation
  9103. * Cross-server interactions are controlled by the host
  9104. * Host process enforces security boundaries
  9105. 4. **Features can be added to servers and clients progressively**
  9106. * Core protocol provides minimal required functionality
  9107. * Additional capabilities can be negotiated as needed
  9108. * Servers and clients evolve independently
  9109. * Protocol designed for future extensibility
  9110. * Backwards compatibility is maintained
  9111. ## Capability Negotiation
  9112. The Model Context Protocol uses a capability-based negotiation system where clients and
  9113. servers explicitly declare their supported features during initialization. Capabilities
  9114. determine which protocol features and primitives are available during a session.
  9115. * Servers declare capabilities like resource subscriptions, tool support, and prompt
  9116. templates
  9117. * Clients declare capabilities like sampling support and notification handling
  9118. * Both parties must respect declared capabilities throughout the session
  9119. * Additional capabilities can be negotiated through extensions to the protocol
  9120. ```mermaid
  9121. sequenceDiagram
  9122. participant Host
  9123. participant Client
  9124. participant Server
  9125. Host->>+Client: Initialize client
  9126. Client->>+Server: Initialize session with capabilities
  9127. Server-->>Client: Respond with supported capabilities
  9128. Note over Host,Server: Active Session with Negotiated Features
  9129. loop Client Requests
  9130. Host->>Client: User- or model-initiated action
  9131. Client->>Server: Request (tools/resources)
  9132. Server-->>Client: Response
  9133. Client-->>Host: Update UI or respond to model
  9134. end
  9135. loop Server Requests
  9136. Server->>Client: Request (sampling)
  9137. Client->>Host: Forward to AI
  9138. Host-->>Client: AI response
  9139. Client-->>Server: Response
  9140. end
  9141. loop Notifications
  9142. Server--)Client: Resource updates
  9143. Client--)Server: Status changes
  9144. end
  9145. Host->>Client: Terminate
  9146. Client->>-Server: End session
  9147. deactivate Server
  9148. ```
  9149. Each capability unlocks specific protocol features for use during the session. For
  9150. example:
  9151. * Implemented [server features](/specification/2025-03-26/server) must be advertised in the
  9152. server's capabilities
  9153. * Emitting resource subscription notifications requires the server to declare
  9154. subscription support
  9155. * Tool invocation requires the server to declare tool capabilities
  9156. * [Sampling](/specification/2025-03-26/client) requires the client to declare support in its
  9157. capabilities
  9158. This capability negotiation ensures clients and servers have a clear understanding of
  9159. supported functionality while maintaining protocol extensibility.
  9160. # Authorization
  9161. Source: https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization
  9162. <Info>**Protocol Revision**: 2025-03-26</Info>
  9163. ## Introduction
  9164. ### Purpose and Scope
  9165. The Model Context Protocol provides authorization capabilities at the transport level,
  9166. enabling MCP clients to make requests to restricted MCP servers on behalf of resource
  9167. owners. This specification defines the authorization flow for HTTP-based transports.
  9168. ### Protocol Requirements
  9169. Authorization is **OPTIONAL** for MCP implementations. When supported:
  9170. * Implementations using an HTTP-based transport **SHOULD** conform to this specification.
  9171. * Implementations using an STDIO transport **SHOULD NOT** follow this specification, and
  9172. instead retrieve credentials from the environment.
  9173. * Implementations using alternative transports **MUST** follow established security best
  9174. practices for their protocol.
  9175. ### Standards Compliance
  9176. This authorization mechanism is based on established specifications listed below, but
  9177. implements a selected subset of their features to ensure security and interoperability
  9178. while maintaining simplicity:
  9179. * [OAuth 2.1 IETF DRAFT](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12)
  9180. * OAuth 2.0 Authorization Server Metadata
  9181. ([RFC8414](https://datatracker.ietf.org/doc/html/rfc8414))
  9182. * OAuth 2.0 Dynamic Client Registration Protocol
  9183. ([RFC7591](https://datatracker.ietf.org/doc/html/rfc7591))
  9184. ## Authorization Flow
  9185. ### Overview
  9186. 1. MCP auth implementations **MUST** implement OAuth 2.1 with appropriate security
  9187. measures for both confidential and public clients.
  9188. 2. MCP auth implementations **SHOULD** support the OAuth 2.0 Dynamic Client Registration
  9189. Protocol ([RFC7591](https://datatracker.ietf.org/doc/html/rfc7591)).
  9190. 3. MCP servers **SHOULD** and MCP clients **MUST** implement OAuth 2.0 Authorization
  9191. Server Metadata ([RFC8414](https://datatracker.ietf.org/doc/html/rfc8414)). Servers
  9192. that do not support Authorization Server Metadata **MUST** follow the default URI
  9193. schema.
  9194. ### OAuth Grant Types
  9195. OAuth specifies different flows or grant types, which are different ways of obtaining an
  9196. access token. Each of these targets different use cases and scenarios.
  9197. MCP servers **SHOULD** support the OAuth grant types that best align with the intended
  9198. audience. For instance:
  9199. 1. Authorization Code: useful when the client is acting on behalf of a (human) end user.
  9200. * For instance, an agent calls an MCP tool implemented by a SaaS system.
  9201. 2. Client Credentials: the client is another application (not a human)
  9202. * For instance, an agent calls a secure MCP tool to check inventory at a specific
  9203. store. No need to impersonate the end user.
  9204. ### Example: authorization code grant
  9205. This demonstrates the OAuth 2.1 flow for the authorization code grant type, used for user
  9206. auth.
  9207. **NOTE**: The following example assumes the MCP server is also functioning as the
  9208. authorization server. However, the authorization server may be deployed as its own
  9209. distinct service.
  9210. A human user completes the OAuth flow through a web browser, obtaining an access token
  9211. that identifies them personally and allows the client to act on their behalf.
  9212. When authorization is required and not yet proven by the client, servers **MUST** respond
  9213. with *HTTP 401 Unauthorized*.
  9214. Clients initiate the
  9215. [OAuth 2.1 IETF DRAFT](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#name-authorization-code-grant)
  9216. authorization flow after receiving the *HTTP 401 Unauthorized*.
  9217. The following demonstrates the basic OAuth 2.1 for public clients using PKCE.
  9218. ```mermaid
  9219. sequenceDiagram
  9220. participant B as User-Agent (Browser)
  9221. participant C as Client
  9222. participant M as MCP Server
  9223. C->>M: MCP Request
  9224. M->>C: HTTP 401 Unauthorized
  9225. Note over C: Generate code_verifier and code_challenge
  9226. C->>B: Open browser with authorization URL + code_challenge
  9227. B->>M: GET /authorize
  9228. Note over M: User logs in and authorizes
  9229. M->>B: Redirect to callback URL with auth code
  9230. B->>C: Callback with authorization code
  9231. C->>M: Token Request with code + code_verifier
  9232. M->>C: Access Token (+ Refresh Token)
  9233. C->>M: MCP Request with Access Token
  9234. Note over C,M: Begin standard MCP message exchange
  9235. ```
  9236. ### Server Metadata Discovery
  9237. For server capability discovery:
  9238. * MCP clients *MUST* follow the OAuth 2.0 Authorization Server Metadata protocol defined
  9239. in [RFC8414](https://datatracker.ietf.org/doc/html/rfc8414).
  9240. * MCP server *SHOULD* follow the OAuth 2.0 Authorization Server Metadata protocol.
  9241. * MCP servers that do not support the OAuth 2.0 Authorization Server Metadata protocol,
  9242. *MUST* support fallback URLs.
  9243. The discovery flow is illustrated below:
  9244. ```mermaid
  9245. sequenceDiagram
  9246. participant C as Client
  9247. participant S as Server
  9248. C->>S: GET /.well-known/oauth-authorization-server
  9249. alt Discovery Success
  9250. S->>C: 200 OK + Metadata Document
  9251. Note over C: Use endpoints from metadata
  9252. else Discovery Failed
  9253. S->>C: 404 Not Found
  9254. Note over C: Fall back to default endpoints
  9255. end
  9256. Note over C: Continue with authorization flow
  9257. ```
  9258. #### Server Metadata Discovery Headers
  9259. MCP clients *SHOULD* include the header `MCP-Protocol-Version: <protocol-version>` during
  9260. Server Metadata Discovery to allow the MCP server to respond based on the MCP protocol
  9261. version.
  9262. For example: `MCP-Protocol-Version: 2024-11-05`
  9263. #### Authorization Base URL
  9264. The authorization base URL **MUST** be determined from the MCP server URL by discarding
  9265. any existing `path` component. For example:
  9266. If the MCP server URL is `https://api.example.com/v1/mcp`, then:
  9267. * The authorization base URL is `https://api.example.com`
  9268. * The metadata endpoint **MUST** be at
  9269. `https://api.example.com/.well-known/oauth-authorization-server`
  9270. This ensures authorization endpoints are consistently located at the root level of the
  9271. domain hosting the MCP server, regardless of any path components in the MCP server URL.
  9272. #### Fallbacks for Servers without Metadata Discovery
  9273. For servers that do not implement OAuth 2.0 Authorization Server Metadata, clients
  9274. **MUST** use the following default endpoint paths relative to the [authorization base
  9275. URL](#authorization-base-url):
  9276. | Endpoint | Default Path | Description |
  9277. | ---------------------- | ------------ | ------------------------------------ |
  9278. | Authorization Endpoint | /authorize | Used for authorization requests |
  9279. | Token Endpoint | /token | Used for token exchange & refresh |
  9280. | Registration Endpoint | /register | Used for dynamic client registration |
  9281. For example, with an MCP server hosted at `https://api.example.com/v1/mcp`, the default
  9282. endpoints would be:
  9283. * `https://api.example.com/authorize`
  9284. * `https://api.example.com/token`
  9285. * `https://api.example.com/register`
  9286. Clients **MUST** first attempt to discover endpoints via the metadata document before
  9287. falling back to default paths. When using default paths, all other protocol requirements
  9288. remain unchanged.
  9289. ### Dynamic Client Registration
  9290. MCP clients and servers **SHOULD** support the
  9291. [OAuth 2.0 Dynamic Client Registration Protocol](https://datatracker.ietf.org/doc/html/rfc7591)
  9292. to allow MCP clients to obtain OAuth client IDs without user interaction. This provides a
  9293. standardized way for clients to automatically register with new servers, which is crucial
  9294. for MCP because:
  9295. * Clients cannot know all possible servers in advance
  9296. * Manual registration would create friction for users
  9297. * It enables seamless connection to new servers
  9298. * Servers can implement their own registration policies
  9299. Any MCP servers that *do not* support Dynamic Client Registration need to provide
  9300. alternative ways to obtain a client ID (and, if applicable, client secret). For one of
  9301. these servers, MCP clients will have to either:
  9302. 1. Hardcode a client ID (and, if applicable, client secret) specifically for that MCP
  9303. server, or
  9304. 2. Present a UI to users that allows them to enter these details, after registering an
  9305. OAuth client themselves (e.g., through a configuration interface hosted by the
  9306. server).
  9307. ### Authorization Flow Steps
  9308. The complete Authorization flow proceeds as follows:
  9309. ```mermaid
  9310. sequenceDiagram
  9311. participant B as User-Agent (Browser)
  9312. participant C as Client
  9313. participant M as MCP Server
  9314. C->>M: GET /.well-known/oauth-authorization-server
  9315. alt Server Supports Discovery
  9316. M->>C: Authorization Server Metadata
  9317. else No Discovery
  9318. M->>C: 404 (Use default endpoints)
  9319. end
  9320. alt Dynamic Client Registration
  9321. C->>M: POST /register
  9322. M->>C: Client Credentials
  9323. end
  9324. Note over C: Generate PKCE Parameters
  9325. C->>B: Open browser with authorization URL + code_challenge
  9326. B->>M: Authorization Request
  9327. Note over M: User /authorizes
  9328. M->>B: Redirect to callback with authorization code
  9329. B->>C: Authorization code callback
  9330. C->>M: Token Request + code_verifier
  9331. M->>C: Access Token (+ Refresh Token)
  9332. C->>M: API Requests with Access Token
  9333. ```
  9334. #### Decision Flow Overview
  9335. ```mermaid
  9336. flowchart TD
  9337. A[Start Auth Flow] --> B{Check Metadata Discovery}
  9338. B -->|Available| C[Use Metadata Endpoints]
  9339. B -->|Not Available| D[Use Default Endpoints]
  9340. C --> G{Check Registration Endpoint}
  9341. D --> G
  9342. G -->|Available| H[Perform Dynamic Registration]
  9343. G -->|Not Available| I[Alternative Registration Required]
  9344. H --> J[Start OAuth Flow]
  9345. I --> J
  9346. J --> K[Generate PKCE Parameters]
  9347. K --> L[Request Authorization]
  9348. L --> M[User Authorization]
  9349. M --> N[Exchange Code for Tokens]
  9350. N --> O[Use Access Token]
  9351. ```
  9352. ### Access Token Usage
  9353. #### Token Requirements
  9354. Access token handling **MUST** conform to
  9355. [OAuth 2.1 Section 5](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5)
  9356. requirements for resource requests. Specifically:
  9357. 1. MCP client **MUST** use the Authorization request header field
  9358. [Section 5.1.1](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.1.1):
  9359. ```
  9360. Authorization: Bearer <access-token>
  9361. ```
  9362. Note that authorization **MUST** be included in every HTTP request from client to server,
  9363. even if they are part of the same logical session.
  9364. 2. Access tokens **MUST NOT** be included in the URI query string
  9365. Example request:
  9366. ```http
  9367. GET /v1/contexts HTTP/1.1
  9368. Host: mcp.example.com
  9369. Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
  9370. ```
  9371. #### Token Handling
  9372. Resource servers **MUST** validate access tokens as described in
  9373. [Section 5.2](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.2).
  9374. If validation fails, servers **MUST** respond according to
  9375. [Section 5.3](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.3)
  9376. error handling requirements. Invalid or expired tokens **MUST** receive a HTTP 401
  9377. response.
  9378. ### Security Considerations
  9379. The following security requirements **MUST** be implemented:
  9380. 1. Clients **MUST** securely store tokens following OAuth 2.0 best practices
  9381. 2. Servers **SHOULD** enforce token expiration and rotation
  9382. 3. All authorization endpoints **MUST** be served over HTTPS
  9383. 4. Servers **MUST** validate redirect URIs to prevent open redirect vulnerabilities
  9384. 5. Redirect URIs **MUST** be either localhost URLs or HTTPS URLs
  9385. ### Error Handling
  9386. Servers **MUST** return appropriate HTTP status codes for authorization errors:
  9387. | Status Code | Description | Usage |
  9388. | ----------- | ------------ | ------------------------------------------ |
  9389. | 401 | Unauthorized | Authorization required or token invalid |
  9390. | 403 | Forbidden | Invalid scopes or insufficient permissions |
  9391. | 400 | Bad Request | Malformed authorization request |
  9392. ### Implementation Requirements
  9393. 1. Implementations **MUST** follow OAuth 2.1 security best practices
  9394. 2. PKCE is **REQUIRED** for all clients
  9395. 3. Token rotation **SHOULD** be implemented for enhanced security
  9396. 4. Token lifetimes **SHOULD** be limited based on security requirements
  9397. ### Third-Party Authorization Flow
  9398. #### Overview
  9399. MCP servers **MAY** support delegated authorization through third-party authorization
  9400. servers. In this flow, the MCP server acts as both an OAuth client (to the third-party
  9401. auth server) and an OAuth authorization server (to the MCP client).
  9402. #### Flow Description
  9403. The third-party authorization flow comprises these steps:
  9404. 1. MCP client initiates standard OAuth flow with MCP server
  9405. 2. MCP server redirects user to third-party authorization server
  9406. 3. User authorizes with third-party server
  9407. 4. Third-party server redirects back to MCP server with authorization code
  9408. 5. MCP server exchanges code for third-party access token
  9409. 6. MCP server generates its own access token bound to the third-party session
  9410. 7. MCP server completes original OAuth flow with MCP client
  9411. ```mermaid
  9412. sequenceDiagram
  9413. participant B as User-Agent (Browser)
  9414. participant C as MCP Client
  9415. participant M as MCP Server
  9416. participant T as Third-Party Auth Server
  9417. C->>M: Initial OAuth Request
  9418. M->>B: Redirect to Third-Party /authorize
  9419. B->>T: Authorization Request
  9420. Note over T: User authorizes
  9421. T->>B: Redirect to MCP Server callback
  9422. B->>M: Authorization code
  9423. M->>T: Exchange code for token
  9424. T->>M: Third-party access token
  9425. Note over M: Generate bound MCP token
  9426. M->>B: Redirect to MCP Client callback
  9427. B->>C: MCP authorization code
  9428. C->>M: Exchange code for token
  9429. M->>C: MCP access token
  9430. ```
  9431. #### Session Binding Requirements
  9432. MCP servers implementing third-party authorization **MUST**:
  9433. 1. Maintain secure mapping between third-party tokens and issued MCP tokens
  9434. 2. Validate third-party token status before honoring MCP tokens
  9435. 3. Implement appropriate token lifecycle management
  9436. 4. Handle third-party token expiration and renewal
  9437. #### Security Considerations
  9438. When implementing third-party authorization, servers **MUST**:
  9439. 1. Validate all redirect URIs
  9440. 2. Securely store third-party credentials
  9441. 3. Implement appropriate session timeout handling
  9442. 4. Consider security implications of token chaining
  9443. 5. Implement proper error handling for third-party auth failures
  9444. ## Best Practices
  9445. #### Local clients as Public OAuth 2.1 Clients
  9446. We strongly recommend that local clients implement OAuth 2.1 as a public client:
  9447. 1. Utilizing code challenges (PKCE) for authorization requests to prevent interception
  9448. attacks
  9449. 2. Implementing secure token storage appropriate for the local system
  9450. 3. Following token refresh best practices to maintain sessions
  9451. 4. Properly handling token expiration and renewal
  9452. #### Authorization Metadata Discovery
  9453. We strongly recommend that all clients implement metadata discovery. This reduces the
  9454. need for users to provide endpoints manually or clients to fallback to the defined
  9455. defaults.
  9456. #### Dynamic Client Registration
  9457. Since clients do not know the set of MCP servers in advance, we strongly recommend the
  9458. implementation of dynamic client registration. This allows applications to automatically
  9459. register with the MCP server, and removes the need for users to obtain client ids
  9460. manually.
  9461. # Overview
  9462. Source: https://modelcontextprotocol.io/specification/2025-03-26/basic/index
  9463. <Info>**Protocol Revision**: 2025-03-26</Info>
  9464. The Model Context Protocol consists of several key components that work together:
  9465. * **Base Protocol**: Core JSON-RPC message types
  9466. * **Lifecycle Management**: Connection initialization, capability negotiation, and
  9467. session control
  9468. * **Server Features**: Resources, prompts, and tools exposed by servers
  9469. * **Client Features**: Sampling and root directory lists provided by clients
  9470. * **Utilities**: Cross-cutting concerns like logging and argument completion
  9471. All implementations **MUST** support the base protocol and lifecycle management
  9472. components. Other components **MAY** be implemented based on the specific needs of the
  9473. application.
  9474. These protocol layers establish clear separation of concerns while enabling rich
  9475. interactions between clients and servers. The modular design allows implementations to
  9476. support exactly the features they need.
  9477. ## Messages
  9478. All messages between MCP clients and servers **MUST** follow the
  9479. [JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines
  9480. these types of messages:
  9481. ### Requests
  9482. Requests are sent from the client to the server or vice versa, to initiate an operation.
  9483. ```typescript
  9484. {
  9485. jsonrpc: "2.0";
  9486. id: string | number;
  9487. method: string;
  9488. params?: {
  9489. [key: string]: unknown;
  9490. };
  9491. }
  9492. ```
  9493. * Requests **MUST** include a string or integer ID.
  9494. * Unlike base JSON-RPC, the ID **MUST NOT** be `null`.
  9495. * The request ID **MUST NOT** have been previously used by the requestor within the same
  9496. session.
  9497. ### Responses
  9498. Responses are sent in reply to requests, containing the result or error of the operation.
  9499. ```typescript
  9500. {
  9501. jsonrpc: "2.0";
  9502. id: string | number;
  9503. result?: {
  9504. [key: string]: unknown;
  9505. }
  9506. error?: {
  9507. code: number;
  9508. message: string;
  9509. data?: unknown;
  9510. }
  9511. }
  9512. ```
  9513. * Responses **MUST** include the same ID as the request they correspond to.
  9514. * **Responses** are further sub-categorized as either **successful results** or
  9515. **errors**. Either a `result` or an `error` **MUST** be set. A response **MUST NOT**
  9516. set both.
  9517. * Results **MAY** follow any JSON object structure, while errors **MUST** include an
  9518. error code and message at minimum.
  9519. * Error codes **MUST** be integers.
  9520. ### Notifications
  9521. Notifications are sent from the client to the server or vice versa, as a one-way message.
  9522. The receiver **MUST NOT** send a response.
  9523. ```typescript
  9524. {
  9525. jsonrpc: "2.0";
  9526. method: string;
  9527. params?: {
  9528. [key: string]: unknown;
  9529. };
  9530. }
  9531. ```
  9532. * Notifications **MUST NOT** include an ID.
  9533. ### Batching
  9534. JSON-RPC also defines a means to
  9535. [batch multiple requests and notifications](https://www.jsonrpc.org/specification#batch),
  9536. by sending them in an array. MCP implementations **MAY** support sending JSON-RPC
  9537. batches, but **MUST** support receiving JSON-RPC batches.
  9538. ## Auth
  9539. MCP provides an [Authorization](/specification/2025-03-26/basic/authorization) framework for use with HTTP.
  9540. Implementations using an HTTP-based transport **SHOULD** conform to this specification,
  9541. whereas implementations using STDIO transport **SHOULD NOT** follow this specification,
  9542. and instead retrieve credentials from the environment.
  9543. Additionally, clients and servers **MAY** negotiate their own custom authentication and
  9544. authorization strategies.
  9545. For further discussions and contributions to the evolution of MCP’s auth mechanisms, join
  9546. us in
  9547. [GitHub Discussions](https://github.com/modelcontextprotocol/specification/discussions)
  9548. to help shape the future of the protocol!
  9549. ## Schema
  9550. The full specification of the protocol is defined as a
  9551. [TypeScript schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/2025-03-26/schema.ts).
  9552. This is the source of truth for all protocol messages and structures.
  9553. There is also a
  9554. [JSON Schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/2025-03-26/schema.json),
  9555. which is automatically generated from the TypeScript source of truth, for use with
  9556. various automated tooling.
  9557. # Lifecycle
  9558. Source: https://modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle
  9559. <Info>**Protocol Revision**: 2025-03-26</Info>
  9560. The Model Context Protocol (MCP) defines a rigorous lifecycle for client-server
  9561. connections that ensures proper capability negotiation and state management.
  9562. 1. **Initialization**: Capability negotiation and protocol version agreement
  9563. 2. **Operation**: Normal protocol communication
  9564. 3. **Shutdown**: Graceful termination of the connection
  9565. ```mermaid
  9566. sequenceDiagram
  9567. participant Client
  9568. participant Server
  9569. Note over Client,Server: Initialization Phase
  9570. activate Client
  9571. Client->>+Server: initialize request
  9572. Server-->>Client: initialize response
  9573. Client--)Server: initialized notification
  9574. Note over Client,Server: Operation Phase
  9575. rect rgb(200, 220, 250)
  9576. note over Client,Server: Normal protocol operations
  9577. end
  9578. Note over Client,Server: Shutdown
  9579. Client--)-Server: Disconnect
  9580. deactivate Server
  9581. Note over Client,Server: Connection closed
  9582. ```
  9583. ## Lifecycle Phases
  9584. ### Initialization
  9585. The initialization phase **MUST** be the first interaction between client and server.
  9586. During this phase, the client and server:
  9587. * Establish protocol version compatibility
  9588. * Exchange and negotiate capabilities
  9589. * Share implementation details
  9590. The client **MUST** initiate this phase by sending an `initialize` request containing:
  9591. * Protocol version supported
  9592. * Client capabilities
  9593. * Client implementation information
  9594. ```json
  9595. {
  9596. "jsonrpc": "2.0",
  9597. "id": 1,
  9598. "method": "initialize",
  9599. "params": {
  9600. "protocolVersion": "2025-03-26",
  9601. "capabilities": {
  9602. "roots": {
  9603. "listChanged": true
  9604. },
  9605. "sampling": {}
  9606. },
  9607. "clientInfo": {
  9608. "name": "ExampleClient",
  9609. "version": "1.0.0"
  9610. }
  9611. }
  9612. }
  9613. ```
  9614. The initialize request **MUST NOT** be part of a JSON-RPC
  9615. [batch](https://www.jsonrpc.org/specification#batch), as other requests and notifications
  9616. are not possible until initialization has completed. This also permits backwards
  9617. compatibility with prior protocol versions that do not explicitly support JSON-RPC
  9618. batches.
  9619. The server **MUST** respond with its own capabilities and information:
  9620. ```json
  9621. {
  9622. "jsonrpc": "2.0",
  9623. "id": 1,
  9624. "result": {
  9625. "protocolVersion": "2025-03-26",
  9626. "capabilities": {
  9627. "logging": {},
  9628. "prompts": {
  9629. "listChanged": true
  9630. },
  9631. "resources": {
  9632. "subscribe": true,
  9633. "listChanged": true
  9634. },
  9635. "tools": {
  9636. "listChanged": true
  9637. }
  9638. },
  9639. "serverInfo": {
  9640. "name": "ExampleServer",
  9641. "version": "1.0.0"
  9642. },
  9643. "instructions": "Optional instructions for the client"
  9644. }
  9645. }
  9646. ```
  9647. After successful initialization, the client **MUST** send an `initialized` notification
  9648. to indicate it is ready to begin normal operations:
  9649. ```json
  9650. {
  9651. "jsonrpc": "2.0",
  9652. "method": "notifications/initialized"
  9653. }
  9654. ```
  9655. * The client **SHOULD NOT** send requests other than
  9656. [pings](/specification/2025-03-26/basic/utilities/ping) before the server has responded to the
  9657. `initialize` request.
  9658. * The server **SHOULD NOT** send requests other than
  9659. [pings](/specification/2025-03-26/basic/utilities/ping) and
  9660. [logging](/specification/2025-03-26/server/utilities/logging) before receiving the `initialized`
  9661. notification.
  9662. #### Version Negotiation
  9663. In the `initialize` request, the client **MUST** send a protocol version it supports.
  9664. This **SHOULD** be the *latest* version supported by the client.
  9665. If the server supports the requested protocol version, it **MUST** respond with the same
  9666. version. Otherwise, the server **MUST** respond with another protocol version it
  9667. supports. This **SHOULD** be the *latest* version supported by the server.
  9668. If the client does not support the version in the server's response, it **SHOULD**
  9669. disconnect.
  9670. #### Capability Negotiation
  9671. Client and server capabilities establish which optional protocol features will be
  9672. available during the session.
  9673. Key capabilities include:
  9674. | Category | Capability | Description |
  9675. | -------- | -------------- | ----------------------------------------------------------------------------------------- |
  9676. | Client | `roots` | Ability to provide filesystem [roots](/specification/2025-03-26/client/roots) |
  9677. | Client | `sampling` | Support for LLM [sampling](/specification/2025-03-26/client/sampling) requests |
  9678. | Client | `experimental` | Describes support for non-standard experimental features |
  9679. | Server | `prompts` | Offers [prompt templates](/specification/2025-03-26/server/prompts) |
  9680. | Server | `resources` | Provides readable [resources](/specification/2025-03-26/server/resources) |
  9681. | Server | `tools` | Exposes callable [tools](/specification/2025-03-26/server/tools) |
  9682. | Server | `logging` | Emits structured [log messages](/specification/2025-03-26/server/utilities/logging) |
  9683. | Server | `completions` | Supports argument [autocompletion](/specification/2025-03-26/server/utilities/completion) |
  9684. | Server | `experimental` | Describes support for non-standard experimental features |
  9685. Capability objects can describe sub-capabilities like:
  9686. * `listChanged`: Support for list change notifications (for prompts, resources, and
  9687. tools)
  9688. * `subscribe`: Support for subscribing to individual items' changes (resources only)
  9689. ### Operation
  9690. During the operation phase, the client and server exchange messages according to the
  9691. negotiated capabilities.
  9692. Both parties **SHOULD**:
  9693. * Respect the negotiated protocol version
  9694. * Only use capabilities that were successfully negotiated
  9695. ### Shutdown
  9696. During the shutdown phase, one side (usually the client) cleanly terminates the protocol
  9697. connection. No specific shutdown messages are defined—instead, the underlying transport
  9698. mechanism should be used to signal connection termination:
  9699. #### stdio
  9700. For the stdio [transport](/specification/2025-03-26/basic/transports), the client **SHOULD** initiate
  9701. shutdown by:
  9702. 1. First, closing the input stream to the child process (the server)
  9703. 2. Waiting for the server to exit, or sending `SIGTERM` if the server does not exit
  9704. within a reasonable time
  9705. 3. Sending `SIGKILL` if the server does not exit within a reasonable time after `SIGTERM`
  9706. The server **MAY** initiate shutdown by closing its output stream to the client and
  9707. exiting.
  9708. #### HTTP
  9709. For HTTP [transports](/specification/2025-03-26/basic/transports), shutdown is indicated by closing the
  9710. associated HTTP connection(s).
  9711. ## Timeouts
  9712. Implementations **SHOULD** establish timeouts for all sent requests, to prevent hung
  9713. connections and resource exhaustion. When the request has not received a success or error
  9714. response within the timeout period, the sender **SHOULD** issue a [cancellation
  9715. notification](/specification/2025-03-26/basic/utilities/cancellation) for that request and stop waiting for
  9716. a response.
  9717. SDKs and other middleware **SHOULD** allow these timeouts to be configured on a
  9718. per-request basis.
  9719. Implementations **MAY** choose to reset the timeout clock when receiving a [progress
  9720. notification](/specification/2025-03-26/basic/utilities/progress) corresponding to the request, as this
  9721. implies that work is actually happening. However, implementations **SHOULD** always
  9722. enforce a maximum timeout, regardless of progress notifications, to limit the impact of a
  9723. misbehaving client or server.
  9724. ## Error Handling
  9725. Implementations **SHOULD** be prepared to handle these error cases:
  9726. * Protocol version mismatch
  9727. * Failure to negotiate required capabilities
  9728. * Request [timeouts](#timeouts)
  9729. Example initialization error:
  9730. ```json
  9731. {
  9732. "jsonrpc": "2.0",
  9733. "id": 1,
  9734. "error": {
  9735. "code": -32602,
  9736. "message": "Unsupported protocol version",
  9737. "data": {
  9738. "supported": ["2024-11-05"],
  9739. "requested": "1.0.0"
  9740. }
  9741. }
  9742. }
  9743. ```
  9744. # Transports
  9745. Source: https://modelcontextprotocol.io/specification/2025-03-26/basic/transports
  9746. <Info>**Protocol Revision**: 2025-03-26</Info>
  9747. MCP uses JSON-RPC to encode messages. JSON-RPC messages **MUST** be UTF-8 encoded.
  9748. The protocol currently defines two standard transport mechanisms for client-server
  9749. communication:
  9750. 1. [stdio](#stdio), communication over standard in and standard out
  9751. 2. [Streamable HTTP](#streamable-http)
  9752. Clients **SHOULD** support stdio whenever possible.
  9753. It is also possible for clients and servers to implement
  9754. [custom transports](#custom-transports) in a pluggable fashion.
  9755. ## stdio
  9756. In the **stdio** transport:
  9757. * The client launches the MCP server as a subprocess.
  9758. * The server reads JSON-RPC messages from its standard input (`stdin`) and sends messages
  9759. to its standard output (`stdout`).
  9760. * Messages may be JSON-RPC requests, notifications, responses—or a JSON-RPC
  9761. [batch](https://www.jsonrpc.org/specification#batch) containing one or more requests
  9762. and/or notifications.
  9763. * Messages are delimited by newlines, and **MUST NOT** contain embedded newlines.
  9764. * The server **MAY** write UTF-8 strings to its standard error (`stderr`) for logging
  9765. purposes. Clients **MAY** capture, forward, or ignore this logging.
  9766. * The server **MUST NOT** write anything to its `stdout` that is not a valid MCP message.
  9767. * The client **MUST NOT** write anything to the server's `stdin` that is not a valid MCP
  9768. message.
  9769. ```mermaid
  9770. sequenceDiagram
  9771. participant Client
  9772. participant Server Process
  9773. Client->>+Server Process: Launch subprocess
  9774. loop Message Exchange
  9775. Client->>Server Process: Write to stdin
  9776. Server Process->>Client: Write to stdout
  9777. Server Process--)Client: Optional logs on stderr
  9778. end
  9779. Client->>Server Process: Close stdin, terminate subprocess
  9780. deactivate Server Process
  9781. ```
  9782. ## Streamable HTTP
  9783. <Info>
  9784. This replaces the [HTTP+SSE
  9785. transport](/specification/2024-11-05/basic/transports#http-with-sse) from
  9786. protocol version 2024-11-05. See the [backwards compatibility](#backwards-compatibility)
  9787. guide below.
  9788. </Info>
  9789. In the **Streamable HTTP** transport, the server operates as an independent process that
  9790. can handle multiple client connections. This transport uses HTTP POST and GET requests.
  9791. Server can optionally make use of
  9792. [Server-Sent Events](https://en.wikipedia.org/wiki/Server-sent_events) (SSE) to stream
  9793. multiple server messages. This permits basic MCP servers, as well as more feature-rich
  9794. servers supporting streaming and server-to-client notifications and requests.
  9795. The server **MUST** provide a single HTTP endpoint path (hereafter referred to as the
  9796. **MCP endpoint**) that supports both POST and GET methods. For example, this could be a
  9797. URL like `https://example.com/mcp`.
  9798. #### Security Warning
  9799. When implementing Streamable HTTP transport:
  9800. 1. Servers **MUST** validate the `Origin` header on all incoming connections to prevent DNS rebinding attacks
  9801. 2. When running locally, servers **SHOULD** bind only to localhost (127.0.0.1) rather than all network interfaces (0.0.0.0)
  9802. 3. Servers **SHOULD** implement proper authentication for all connections
  9803. Without these protections, attackers could use DNS rebinding to interact with local MCP servers from remote websites.
  9804. ### Sending Messages to the Server
  9805. Every JSON-RPC message sent from the client **MUST** be a new HTTP POST request to the
  9806. MCP endpoint.
  9807. 1. The client **MUST** use HTTP POST to send JSON-RPC messages to the MCP endpoint.
  9808. 2. The client **MUST** include an `Accept` header, listing both `application/json` and
  9809. `text/event-stream` as supported content types.
  9810. 3. The body of the POST request **MUST** be one of the following:
  9811. * A single JSON-RPC *request*, *notification*, or *response*
  9812. * An array [batching](https://www.jsonrpc.org/specification#batch) one or more
  9813. *requests and/or notifications*
  9814. * An array [batching](https://www.jsonrpc.org/specification#batch) one or more
  9815. *responses*
  9816. 4. If the input consists solely of (any number of) JSON-RPC *responses* or
  9817. *notifications*:
  9818. * If the server accepts the input, the server **MUST** return HTTP status code 202
  9819. Accepted with no body.
  9820. * If the server cannot accept the input, it **MUST** return an HTTP error status code
  9821. (e.g., 400 Bad Request). The HTTP response body **MAY** comprise a JSON-RPC *error
  9822. response* that has no `id`.
  9823. 5. If the input contains any number of JSON-RPC *requests*, the server **MUST** either
  9824. return `Content-Type: text/event-stream`, to initiate an SSE stream, or
  9825. `Content-Type: application/json`, to return one JSON object. The client **MUST**
  9826. support both these cases.
  9827. 6. If the server initiates an SSE stream:
  9828. * The SSE stream **SHOULD** eventually include one JSON-RPC *response* per each
  9829. JSON-RPC *request* sent in the POST body. These *responses* **MAY** be
  9830. [batched](https://www.jsonrpc.org/specification#batch).
  9831. * The server **MAY** send JSON-RPC *requests* and *notifications* before sending a
  9832. JSON-RPC *response*. These messages **SHOULD** relate to the originating client
  9833. *request*. These *requests* and *notifications* **MAY** be
  9834. [batched](https://www.jsonrpc.org/specification#batch).
  9835. * The server **SHOULD NOT** close the SSE stream before sending a JSON-RPC *response*
  9836. per each received JSON-RPC *request*, unless the [session](#session-management)
  9837. expires.
  9838. * After all JSON-RPC *responses* have been sent, the server **SHOULD** close the SSE
  9839. stream.
  9840. * Disconnection **MAY** occur at any time (e.g., due to network conditions).
  9841. Therefore:
  9842. * Disconnection **SHOULD NOT** be interpreted as the client cancelling its request.
  9843. * To cancel, the client **SHOULD** explicitly send an MCP `CancelledNotification`.
  9844. * To avoid message loss due to disconnection, the server **MAY** make the stream
  9845. [resumable](#resumability-and-redelivery).
  9846. ### Listening for Messages from the Server
  9847. 1. The client **MAY** issue an HTTP GET to the MCP endpoint. This can be used to open an
  9848. SSE stream, allowing the server to communicate to the client, without the client first
  9849. sending data via HTTP POST.
  9850. 2. The client **MUST** include an `Accept` header, listing `text/event-stream` as a
  9851. supported content type.
  9852. 3. The server **MUST** either return `Content-Type: text/event-stream` in response to
  9853. this HTTP GET, or else return HTTP 405 Method Not Allowed, indicating that the server
  9854. does not offer an SSE stream at this endpoint.
  9855. 4. If the server initiates an SSE stream:
  9856. * The server **MAY** send JSON-RPC *requests* and *notifications* on the stream. These
  9857. *requests* and *notifications* **MAY** be
  9858. [batched](https://www.jsonrpc.org/specification#batch).
  9859. * These messages **SHOULD** be unrelated to any concurrently-running JSON-RPC
  9860. *request* from the client.
  9861. * The server **MUST NOT** send a JSON-RPC *response* on the stream **unless**
  9862. [resuming](#resumability-and-redelivery) a stream associated with a previous client
  9863. request.
  9864. * The server **MAY** close the SSE stream at any time.
  9865. * The client **MAY** close the SSE stream at any time.
  9866. ### Multiple Connections
  9867. 1. The client **MAY** remain connected to multiple SSE streams simultaneously.
  9868. 2. The server **MUST** send each of its JSON-RPC messages on only one of the connected
  9869. streams; that is, it **MUST NOT** broadcast the same message across multiple streams.
  9870. * The risk of message loss **MAY** be mitigated by making the stream
  9871. [resumable](#resumability-and-redelivery).
  9872. ### Resumability and Redelivery
  9873. To support resuming broken connections, and redelivering messages that might otherwise be
  9874. lost:
  9875. 1. Servers **MAY** attach an `id` field to their SSE events, as described in the
  9876. [SSE standard](https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation).
  9877. * If present, the ID **MUST** be globally unique across all streams within that
  9878. [session](#session-management)—or all streams with that specific client, if session
  9879. management is not in use.
  9880. 2. If the client wishes to resume after a broken connection, it **SHOULD** issue an HTTP
  9881. GET to the MCP endpoint, and include the
  9882. [`Last-Event-ID`](https://html.spec.whatwg.org/multipage/server-sent-events.html#the-last-event-id-header)
  9883. header to indicate the last event ID it received.
  9884. * The server **MAY** use this header to replay messages that would have been sent
  9885. after the last event ID, *on the stream that was disconnected*, and to resume the
  9886. stream from that point.
  9887. * The server **MUST NOT** replay messages that would have been delivered on a
  9888. different stream.
  9889. In other words, these event IDs should be assigned by servers on a *per-stream* basis, to
  9890. act as a cursor within that particular stream.
  9891. ### Session Management
  9892. An MCP "session" consists of logically related interactions between a client and a
  9893. server, beginning with the [initialization phase](/specification/2025-03-26/basic/lifecycle). To support
  9894. servers which want to establish stateful sessions:
  9895. 1. A server using the Streamable HTTP transport **MAY** assign a session ID at
  9896. initialization time, by including it in an `Mcp-Session-Id` header on the HTTP
  9897. response containing the `InitializeResult`.
  9898. * The session ID **SHOULD** be globally unique and cryptographically secure (e.g., a
  9899. securely generated UUID, a JWT, or a cryptographic hash).
  9900. * The session ID **MUST** only contain visible ASCII characters (ranging from 0x21 to
  9901. 0x7E).
  9902. 2. If an `Mcp-Session-Id` is returned by the server during initialization, clients using
  9903. the Streamable HTTP transport **MUST** include it in the `Mcp-Session-Id` header on
  9904. all of their subsequent HTTP requests.
  9905. * Servers that require a session ID **SHOULD** respond to requests without an
  9906. `Mcp-Session-Id` header (other than initialization) with HTTP 400 Bad Request.
  9907. 3. The server **MAY** terminate the session at any time, after which it **MUST** respond
  9908. to requests containing that session ID with HTTP 404 Not Found.
  9909. 4. When a client receives HTTP 404 in response to a request containing an
  9910. `Mcp-Session-Id`, it **MUST** start a new session by sending a new `InitializeRequest`
  9911. without a session ID attached.
  9912. 5. Clients that no longer need a particular session (e.g., because the user is leaving
  9913. the client application) **SHOULD** send an HTTP DELETE to the MCP endpoint with the
  9914. `Mcp-Session-Id` header, to explicitly terminate the session.
  9915. * The server **MAY** respond to this request with HTTP 405 Method Not Allowed,
  9916. indicating that the server does not allow clients to terminate sessions.
  9917. ### Sequence Diagram
  9918. ```mermaid
  9919. sequenceDiagram
  9920. participant Client
  9921. participant Server
  9922. note over Client, Server: initialization
  9923. Client->>+Server: POST InitializeRequest
  9924. Server->>-Client: InitializeResponse<br>Mcp-Session-Id: 1868a90c...
  9925. Client->>+Server: POST InitializedNotification<br>Mcp-Session-Id: 1868a90c...
  9926. Server->>-Client: 202 Accepted
  9927. note over Client, Server: client requests
  9928. Client->>+Server: POST ... request ...<br>Mcp-Session-Id: 1868a90c...
  9929. alt single HTTP response
  9930. Server->>Client: ... response ...
  9931. else server opens SSE stream
  9932. loop while connection remains open
  9933. Server-)Client: ... SSE messages from server ...
  9934. end
  9935. Server-)Client: SSE event: ... response ...
  9936. end
  9937. deactivate Server
  9938. note over Client, Server: client notifications/responses
  9939. Client->>+Server: POST ... notification/response ...<br>Mcp-Session-Id: 1868a90c...
  9940. Server->>-Client: 202 Accepted
  9941. note over Client, Server: server requests
  9942. Client->>+Server: GET<br>Mcp-Session-Id: 1868a90c...
  9943. loop while connection remains open
  9944. Server-)Client: ... SSE messages from server ...
  9945. end
  9946. deactivate Server
  9947. ```
  9948. ### Backwards Compatibility
  9949. Clients and servers can maintain backwards compatibility with the deprecated [HTTP+SSE
  9950. transport](/specification/2024-11-05/basic/transports#http-with-sse) (from
  9951. protocol version 2024-11-05) as follows:
  9952. **Servers** wanting to support older clients should:
  9953. * Continue to host both the SSE and POST endpoints of the old transport, alongside the
  9954. new "MCP endpoint" defined for the Streamable HTTP transport.
  9955. * It is also possible to combine the old POST endpoint and the new MCP endpoint, but
  9956. this may introduce unneeded complexity.
  9957. **Clients** wanting to support older servers should:
  9958. 1. Accept an MCP server URL from the user, which may point to either a server using the
  9959. old transport or the new transport.
  9960. 2. Attempt to POST an `InitializeRequest` to the server URL, with an `Accept` header as
  9961. defined above:
  9962. * If it succeeds, the client can assume this is a server supporting the new Streamable
  9963. HTTP transport.
  9964. * If it fails with an HTTP 4xx status code (e.g., 405 Method Not Allowed or 404 Not
  9965. Found):
  9966. * Issue a GET request to the server URL, expecting that this will open an SSE stream
  9967. and return an `endpoint` event as the first event.
  9968. * When the `endpoint` event arrives, the client can assume this is a server running
  9969. the old HTTP+SSE transport, and should use that transport for all subsequent
  9970. communication.
  9971. ## Custom Transports
  9972. Clients and servers **MAY** implement additional custom transport mechanisms to suit
  9973. their specific needs. The protocol is transport-agnostic and can be implemented over any
  9974. communication channel that supports bidirectional message exchange.
  9975. Implementers who choose to support custom transports **MUST** ensure they preserve the
  9976. JSON-RPC message format and lifecycle requirements defined by MCP. Custom transports
  9977. **SHOULD** document their specific connection establishment and message exchange patterns
  9978. to aid interoperability.
  9979. # Cancellation
  9980. Source: https://modelcontextprotocol.io/specification/2025-03-26/basic/utilities/cancellation
  9981. <Info>**Protocol Revision**: 2025-03-26</Info>
  9982. The Model Context Protocol (MCP) supports optional cancellation of in-progress requests
  9983. through notification messages. Either side can send a cancellation notification to
  9984. indicate that a previously-issued request should be terminated.
  9985. ## Cancellation Flow
  9986. When a party wants to cancel an in-progress request, it sends a `notifications/cancelled`
  9987. notification containing:
  9988. * The ID of the request to cancel
  9989. * An optional reason string that can be logged or displayed
  9990. ```json
  9991. {
  9992. "jsonrpc": "2.0",
  9993. "method": "notifications/cancelled",
  9994. "params": {
  9995. "requestId": "123",
  9996. "reason": "User requested cancellation"
  9997. }
  9998. }
  9999. ```
  10000. ## Behavior Requirements
  10001. 1. Cancellation notifications **MUST** only reference requests that:
  10002. * Were previously issued in the same direction
  10003. * Are believed to still be in-progress
  10004. 2. The `initialize` request **MUST NOT** be cancelled by clients
  10005. 3. Receivers of cancellation notifications **SHOULD**:
  10006. * Stop processing the cancelled request
  10007. * Free associated resources
  10008. * Not send a response for the cancelled request
  10009. 4. Receivers **MAY** ignore cancellation notifications if:
  10010. * The referenced request is unknown
  10011. * Processing has already completed
  10012. * The request cannot be cancelled
  10013. 5. The sender of the cancellation notification **SHOULD** ignore any response to the
  10014. request that arrives afterward
  10015. ## Timing Considerations
  10016. Due to network latency, cancellation notifications may arrive after request processing
  10017. has completed, and potentially after a response has already been sent.
  10018. Both parties **MUST** handle these race conditions gracefully:
  10019. ```mermaid
  10020. sequenceDiagram
  10021. participant Client
  10022. participant Server
  10023. Client->>Server: Request (ID: 123)
  10024. Note over Server: Processing starts
  10025. Client--)Server: notifications/cancelled (ID: 123)
  10026. alt
  10027. Note over Server: Processing may have<br/>completed before<br/>cancellation arrives
  10028. else If not completed
  10029. Note over Server: Stop processing
  10030. end
  10031. ```
  10032. ## Implementation Notes
  10033. * Both parties **SHOULD** log cancellation reasons for debugging
  10034. * Application UIs **SHOULD** indicate when cancellation is requested
  10035. ## Error Handling
  10036. Invalid cancellation notifications **SHOULD** be ignored:
  10037. * Unknown request IDs
  10038. * Already completed requests
  10039. * Malformed notifications
  10040. This maintains the "fire and forget" nature of notifications while allowing for race
  10041. conditions in asynchronous communication.
  10042. # Ping
  10043. Source: https://modelcontextprotocol.io/specification/2025-03-26/basic/utilities/ping
  10044. <Info>**Protocol Revision**: 2025-03-26</Info>
  10045. The Model Context Protocol includes an optional ping mechanism that allows either party
  10046. to verify that their counterpart is still responsive and the connection is alive.
  10047. ## Overview
  10048. The ping functionality is implemented through a simple request/response pattern. Either
  10049. the client or server can initiate a ping by sending a `ping` request.
  10050. ## Message Format
  10051. A ping request is a standard JSON-RPC request with no parameters:
  10052. ```json
  10053. {
  10054. "jsonrpc": "2.0",
  10055. "id": "123",
  10056. "method": "ping"
  10057. }
  10058. ```
  10059. ## Behavior Requirements
  10060. 1. The receiver **MUST** respond promptly with an empty response:
  10061. ```json
  10062. {
  10063. "jsonrpc": "2.0",
  10064. "id": "123",
  10065. "result": {}
  10066. }
  10067. ```
  10068. 2. If no response is received within a reasonable timeout period, the sender **MAY**:
  10069. * Consider the connection stale
  10070. * Terminate the connection
  10071. * Attempt reconnection procedures
  10072. ## Usage Patterns
  10073. ```mermaid
  10074. sequenceDiagram
  10075. participant Sender
  10076. participant Receiver
  10077. Sender->>Receiver: ping request
  10078. Receiver->>Sender: empty response
  10079. ```
  10080. ## Implementation Considerations
  10081. * Implementations **SHOULD** periodically issue pings to detect connection health
  10082. * The frequency of pings **SHOULD** be configurable
  10083. * Timeouts **SHOULD** be appropriate for the network environment
  10084. * Excessive pinging **SHOULD** be avoided to reduce network overhead
  10085. ## Error Handling
  10086. * Timeouts **SHOULD** be treated as connection failures
  10087. * Multiple failed pings **MAY** trigger connection reset
  10088. * Implementations **SHOULD** log ping failures for diagnostics
  10089. # Progress
  10090. Source: https://modelcontextprotocol.io/specification/2025-03-26/basic/utilities/progress
  10091. <Info>**Protocol Revision**: 2025-03-26</Info>
  10092. The Model Context Protocol (MCP) supports optional progress tracking for long-running
  10093. operations through notification messages. Either side can send progress notifications to
  10094. provide updates about operation status.
  10095. ## Progress Flow
  10096. When a party wants to *receive* progress updates for a request, it includes a
  10097. `progressToken` in the request metadata.
  10098. * Progress tokens **MUST** be a string or integer value
  10099. * Progress tokens can be chosen by the sender using any means, but **MUST** be unique
  10100. across all active requests.
  10101. ```json
  10102. {
  10103. "jsonrpc": "2.0",
  10104. "id": 1,
  10105. "method": "some_method",
  10106. "params": {
  10107. "_meta": {
  10108. "progressToken": "abc123"
  10109. }
  10110. }
  10111. }
  10112. ```
  10113. The receiver **MAY** then send progress notifications containing:
  10114. * The original progress token
  10115. * The current progress value so far
  10116. * An optional "total" value
  10117. * An optional "message" value
  10118. ```json
  10119. {
  10120. "jsonrpc": "2.0",
  10121. "method": "notifications/progress",
  10122. "params": {
  10123. "progressToken": "abc123",
  10124. "progress": 50,
  10125. "total": 100,
  10126. "message": "Reticulating splines..."
  10127. }
  10128. }
  10129. ```
  10130. * The `progress` value **MUST** increase with each notification, even if the total is
  10131. unknown.
  10132. * The `progress` and the `total` values **MAY** be floating point.
  10133. * The `message` field **SHOULD** provide relevant human readable progress information.
  10134. ## Behavior Requirements
  10135. 1. Progress notifications **MUST** only reference tokens that:
  10136. * Were provided in an active request
  10137. * Are associated with an in-progress operation
  10138. 2. Receivers of progress requests **MAY**:
  10139. * Choose not to send any progress notifications
  10140. * Send notifications at whatever frequency they deem appropriate
  10141. * Omit the total value if unknown
  10142. ```mermaid
  10143. sequenceDiagram
  10144. participant Sender
  10145. participant Receiver
  10146. Note over Sender,Receiver: Request with progress token
  10147. Sender->>Receiver: Method request with progressToken
  10148. Note over Sender,Receiver: Progress updates
  10149. loop Progress Updates
  10150. Receiver-->>Sender: Progress notification (0.2/1.0)
  10151. Receiver-->>Sender: Progress notification (0.6/1.0)
  10152. Receiver-->>Sender: Progress notification (1.0/1.0)
  10153. end
  10154. Note over Sender,Receiver: Operation complete
  10155. Receiver->>Sender: Method response
  10156. ```
  10157. ## Implementation Notes
  10158. * Senders and receivers **SHOULD** track active progress tokens
  10159. * Both parties **SHOULD** implement rate limiting to prevent flooding
  10160. * Progress notifications **MUST** stop after completion
  10161. # Key Changes
  10162. Source: https://modelcontextprotocol.io/specification/2025-03-26/changelog
  10163. This document lists changes made to the Model Context Protocol (MCP) specification since
  10164. the previous revision, [2024-11-05](/specification/2024-11-05).
  10165. ## Major changes
  10166. 1. Added a comprehensive **[authorization framework](/specification/2025-03-26/basic/authorization)**
  10167. based on OAuth 2.1 (PR
  10168. [#133](https://github.com/modelcontextprotocol/specification/pull/133))
  10169. 2. Replaced the previous HTTP+SSE transport with a more flexible **[Streamable HTTP
  10170. transport](/specification/2025-03-26/basic/transports#streamable-http)** (PR
  10171. [#206](https://github.com/modelcontextprotocol/specification/pull/206))
  10172. 3. Added support for JSON-RPC **[batching](https://www.jsonrpc.org/specification#batch)**
  10173. (PR [#228](https://github.com/modelcontextprotocol/specification/pull/228))
  10174. 4. Added comprehensive **tool annotations** for better describing tool behavior, like
  10175. whether it is read-only or destructive (PR
  10176. [#185](https://github.com/modelcontextprotocol/specification/pull/185))
  10177. ## Other schema changes
  10178. * Added `message` field to `ProgressNotification` to provide descriptive status updates
  10179. * Added support for audio data, joining the existing text and image content types
  10180. * Added `completions` capability to explicitly indicate support for argument
  10181. autocompletion suggestions
  10182. See
  10183. [the updated schema](http://github.com/modelcontextprotocol/specification/tree/main/schema/2025-03-26/schema.ts)
  10184. for more details.
  10185. ## Full changelog
  10186. For a complete list of all changes that have been made since the last protocol revision,
  10187. [see GitHub](https://github.com/modelcontextprotocol/specification/compare/2024-11-05...2025-03-26).
  10188. # Roots
  10189. Source: https://modelcontextprotocol.io/specification/2025-03-26/client/roots
  10190. <Info>**Protocol Revision**: 2025-03-26</Info>
  10191. The Model Context Protocol (MCP) provides a standardized way for clients to expose
  10192. filesystem "roots" to servers. Roots define the boundaries of where servers can operate
  10193. within the filesystem, allowing them to understand which directories and files they have
  10194. access to. Servers can request the list of roots from supporting clients and receive
  10195. notifications when that list changes.
  10196. ## User Interaction Model
  10197. Roots in MCP are typically exposed through workspace or project configuration interfaces.
  10198. For example, implementations could offer a workspace/project picker that allows users to
  10199. select directories and files the server should have access to. This can be combined with
  10200. automatic workspace detection from version control systems or project files.
  10201. However, implementations are free to expose roots through any interface pattern that
  10202. suits their needs—the protocol itself does not mandate any specific user
  10203. interaction model.
  10204. ## Capabilities
  10205. Clients that support roots **MUST** declare the `roots` capability during
  10206. [initialization](/specification/2025-03-26/basic/lifecycle#initialization):
  10207. ```json
  10208. {
  10209. "capabilities": {
  10210. "roots": {
  10211. "listChanged": true
  10212. }
  10213. }
  10214. }
  10215. ```
  10216. `listChanged` indicates whether the client will emit notifications when the list of roots
  10217. changes.
  10218. ## Protocol Messages
  10219. ### Listing Roots
  10220. To retrieve roots, servers send a `roots/list` request:
  10221. **Request:**
  10222. ```json
  10223. {
  10224. "jsonrpc": "2.0",
  10225. "id": 1,
  10226. "method": "roots/list"
  10227. }
  10228. ```
  10229. **Response:**
  10230. ```json
  10231. {
  10232. "jsonrpc": "2.0",
  10233. "id": 1,
  10234. "result": {
  10235. "roots": [
  10236. {
  10237. "uri": "file:///home/user/projects/myproject",
  10238. "name": "My Project"
  10239. }
  10240. ]
  10241. }
  10242. }
  10243. ```
  10244. ### Root List Changes
  10245. When roots change, clients that support `listChanged` **MUST** send a notification:
  10246. ```json
  10247. {
  10248. "jsonrpc": "2.0",
  10249. "method": "notifications/roots/list_changed"
  10250. }
  10251. ```
  10252. ## Message Flow
  10253. ```mermaid
  10254. sequenceDiagram
  10255. participant Server
  10256. participant Client
  10257. Note over Server,Client: Discovery
  10258. Server->>Client: roots/list
  10259. Client-->>Server: Available roots
  10260. Note over Server,Client: Changes
  10261. Client--)Server: notifications/roots/list_changed
  10262. Server->>Client: roots/list
  10263. Client-->>Server: Updated roots
  10264. ```
  10265. ## Data Types
  10266. ### Root
  10267. A root definition includes:
  10268. * `uri`: Unique identifier for the root. This **MUST** be a `file://` URI in the current
  10269. specification.
  10270. * `name`: Optional human-readable name for display purposes.
  10271. Example roots for different use cases:
  10272. #### Project Directory
  10273. ```json
  10274. {
  10275. "uri": "file:///home/user/projects/myproject",
  10276. "name": "My Project"
  10277. }
  10278. ```
  10279. #### Multiple Repositories
  10280. ```json
  10281. [
  10282. {
  10283. "uri": "file:///home/user/repos/frontend",
  10284. "name": "Frontend Repository"
  10285. },
  10286. {
  10287. "uri": "file:///home/user/repos/backend",
  10288. "name": "Backend Repository"
  10289. }
  10290. ]
  10291. ```
  10292. ## Error Handling
  10293. Clients **SHOULD** return standard JSON-RPC errors for common failure cases:
  10294. * Client does not support roots: `-32601` (Method not found)
  10295. * Internal errors: `-32603`
  10296. Example error:
  10297. ```json
  10298. {
  10299. "jsonrpc": "2.0",
  10300. "id": 1,
  10301. "error": {
  10302. "code": -32601,
  10303. "message": "Roots not supported",
  10304. "data": {
  10305. "reason": "Client does not have roots capability"
  10306. }
  10307. }
  10308. }
  10309. ```
  10310. ## Security Considerations
  10311. 1. Clients **MUST**:
  10312. * Only expose roots with appropriate permissions
  10313. * Validate all root URIs to prevent path traversal
  10314. * Implement proper access controls
  10315. * Monitor root accessibility
  10316. 2. Servers **SHOULD**:
  10317. * Handle cases where roots become unavailable
  10318. * Respect root boundaries during operations
  10319. * Validate all paths against provided roots
  10320. ## Implementation Guidelines
  10321. 1. Clients **SHOULD**:
  10322. * Prompt users for consent before exposing roots to servers
  10323. * Provide clear user interfaces for root management
  10324. * Validate root accessibility before exposing
  10325. * Monitor for root changes
  10326. 2. Servers **SHOULD**:
  10327. * Check for roots capability before usage
  10328. * Handle root list changes gracefully
  10329. * Respect root boundaries in operations
  10330. * Cache root information appropriately
  10331. # Sampling
  10332. Source: https://modelcontextprotocol.io/specification/2025-03-26/client/sampling
  10333. <Info>**Protocol Revision**: 2025-03-26</Info>
  10334. The Model Context Protocol (MCP) provides a standardized way for servers to request LLM
  10335. sampling ("completions" or "generations") from language models via clients. This flow
  10336. allows clients to maintain control over model access, selection, and permissions while
  10337. enabling servers to leverage AI capabilities—with no server API keys necessary.
  10338. Servers can request text, audio, or image-based interactions and optionally include
  10339. context from MCP servers in their prompts.
  10340. ## User Interaction Model
  10341. Sampling in MCP allows servers to implement agentic behaviors, by enabling LLM calls to
  10342. occur *nested* inside other MCP server features.
  10343. Implementations are free to expose sampling through any interface pattern that suits
  10344. their needs—the protocol itself does not mandate any specific user interaction
  10345. model.
  10346. <Warning>
  10347. For trust & safety and security, there **SHOULD** always
  10348. be a human in the loop with the ability to deny sampling requests.
  10349. Applications **SHOULD**:
  10350. * Provide UI that makes it easy and intuitive to review sampling requests
  10351. * Allow users to view and edit prompts before sending
  10352. * Present generated responses for review before delivery
  10353. </Warning>
  10354. ## Capabilities
  10355. Clients that support sampling **MUST** declare the `sampling` capability during
  10356. [initialization](/specification/2025-03-26/basic/lifecycle#initialization):
  10357. ```json
  10358. {
  10359. "capabilities": {
  10360. "sampling": {}
  10361. }
  10362. }
  10363. ```
  10364. ## Protocol Messages
  10365. ### Creating Messages
  10366. To request a language model generation, servers send a `sampling/createMessage` request:
  10367. **Request:**
  10368. ```json
  10369. {
  10370. "jsonrpc": "2.0",
  10371. "id": 1,
  10372. "method": "sampling/createMessage",
  10373. "params": {
  10374. "messages": [
  10375. {
  10376. "role": "user",
  10377. "content": {
  10378. "type": "text",
  10379. "text": "What is the capital of France?"
  10380. }
  10381. }
  10382. ],
  10383. "modelPreferences": {
  10384. "hints": [
  10385. {
  10386. "name": "claude-3-sonnet"
  10387. }
  10388. ],
  10389. "intelligencePriority": 0.8,
  10390. "speedPriority": 0.5
  10391. },
  10392. "systemPrompt": "You are a helpful assistant.",
  10393. "maxTokens": 100
  10394. }
  10395. }
  10396. ```
  10397. **Response:**
  10398. ```json
  10399. {
  10400. "jsonrpc": "2.0",
  10401. "id": 1,
  10402. "result": {
  10403. "role": "assistant",
  10404. "content": {
  10405. "type": "text",
  10406. "text": "The capital of France is Paris."
  10407. },
  10408. "model": "claude-3-sonnet-20240307",
  10409. "stopReason": "endTurn"
  10410. }
  10411. }
  10412. ```
  10413. ## Message Flow
  10414. ```mermaid
  10415. sequenceDiagram
  10416. participant Server
  10417. participant Client
  10418. participant User
  10419. participant LLM
  10420. Note over Server,Client: Server initiates sampling
  10421. Server->>Client: sampling/createMessage
  10422. Note over Client,User: Human-in-the-loop review
  10423. Client->>User: Present request for approval
  10424. User-->>Client: Review and approve/modify
  10425. Note over Client,LLM: Model interaction
  10426. Client->>LLM: Forward approved request
  10427. LLM-->>Client: Return generation
  10428. Note over Client,User: Response review
  10429. Client->>User: Present response for approval
  10430. User-->>Client: Review and approve/modify
  10431. Note over Server,Client: Complete request
  10432. Client-->>Server: Return approved response
  10433. ```
  10434. ## Data Types
  10435. ### Messages
  10436. Sampling messages can contain:
  10437. #### Text Content
  10438. ```json
  10439. {
  10440. "type": "text",
  10441. "text": "The message content"
  10442. }
  10443. ```
  10444. #### Image Content
  10445. ```json
  10446. {
  10447. "type": "image",
  10448. "data": "base64-encoded-image-data",
  10449. "mimeType": "image/jpeg"
  10450. }
  10451. ```
  10452. #### Audio Content
  10453. ```json
  10454. {
  10455. "type": "audio",
  10456. "data": "base64-encoded-audio-data",
  10457. "mimeType": "audio/wav"
  10458. }
  10459. ```
  10460. ### Model Preferences
  10461. Model selection in MCP requires careful abstraction since servers and clients may use
  10462. different AI providers with distinct model offerings. A server cannot simply request a
  10463. specific model by name since the client may not have access to that exact model or may
  10464. prefer to use a different provider's equivalent model.
  10465. To solve this, MCP implements a preference system that combines abstract capability
  10466. priorities with optional model hints:
  10467. #### Capability Priorities
  10468. Servers express their needs through three normalized priority values (0-1):
  10469. * `costPriority`: How important is minimizing costs? Higher values prefer cheaper models.
  10470. * `speedPriority`: How important is low latency? Higher values prefer faster models.
  10471. * `intelligencePriority`: How important are advanced capabilities? Higher values prefer
  10472. more capable models.
  10473. #### Model Hints
  10474. While priorities help select models based on characteristics, `hints` allow servers to
  10475. suggest specific models or model families:
  10476. * Hints are treated as substrings that can match model names flexibly
  10477. * Multiple hints are evaluated in order of preference
  10478. * Clients **MAY** map hints to equivalent models from different providers
  10479. * Hints are advisory—clients make final model selection
  10480. For example:
  10481. ```json
  10482. {
  10483. "hints": [
  10484. { "name": "claude-3-sonnet" }, // Prefer Sonnet-class models
  10485. { "name": "claude" } // Fall back to any Claude model
  10486. ],
  10487. "costPriority": 0.3, // Cost is less important
  10488. "speedPriority": 0.8, // Speed is very important
  10489. "intelligencePriority": 0.5 // Moderate capability needs
  10490. }
  10491. ```
  10492. The client processes these preferences to select an appropriate model from its available
  10493. options. For instance, if the client doesn't have access to Claude models but has Gemini,
  10494. it might map the sonnet hint to `gemini-1.5-pro` based on similar capabilities.
  10495. ## Error Handling
  10496. Clients **SHOULD** return errors for common failure cases:
  10497. Example error:
  10498. ```json
  10499. {
  10500. "jsonrpc": "2.0",
  10501. "id": 1,
  10502. "error": {
  10503. "code": -1,
  10504. "message": "User rejected sampling request"
  10505. }
  10506. }
  10507. ```
  10508. ## Security Considerations
  10509. 1. Clients **SHOULD** implement user approval controls
  10510. 2. Both parties **SHOULD** validate message content
  10511. 3. Clients **SHOULD** respect model preference hints
  10512. 4. Clients **SHOULD** implement rate limiting
  10513. 5. Both parties **MUST** handle sensitive data appropriately
  10514. # Specification
  10515. Source: https://modelcontextprotocol.io/specification/2025-03-26/index
  10516. [Model Context Protocol](https://modelcontextprotocol.io) (MCP) is an open protocol that
  10517. enables seamless integration between LLM applications and external data sources and
  10518. tools. Whether you're building an AI-powered IDE, enhancing a chat interface, or creating
  10519. custom AI workflows, MCP provides a standardized way to connect LLMs with the context
  10520. they need.
  10521. This specification defines the authoritative protocol requirements, based on the
  10522. TypeScript schema in
  10523. [schema.ts](https://github.com/modelcontextprotocol/specification/blob/main/schema/2025-03-26/schema.ts).
  10524. For implementation guides and examples, visit
  10525. [modelcontextprotocol.io](https://modelcontextprotocol.io).
  10526. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD
  10527. NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be
  10528. interpreted as described in [BCP 14](https://datatracker.ietf.org/doc/html/bcp14)
  10529. \[[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)]
  10530. \[[RFC8174](https://datatracker.ietf.org/doc/html/rfc8174)] when, and only when, they
  10531. appear in all capitals, as shown here.
  10532. ## Overview
  10533. MCP provides a standardized way for applications to:
  10534. * Share contextual information with language models
  10535. * Expose tools and capabilities to AI systems
  10536. * Build composable integrations and workflows
  10537. The protocol uses [JSON-RPC](https://www.jsonrpc.org/) 2.0 messages to establish
  10538. communication between:
  10539. * **Hosts**: LLM applications that initiate connections
  10540. * **Clients**: Connectors within the host application
  10541. * **Servers**: Services that provide context and capabilities
  10542. MCP takes some inspiration from the
  10543. [Language Server Protocol](https://microsoft.github.io/language-server-protocol/), which
  10544. standardizes how to add support for programming languages across a whole ecosystem of
  10545. development tools. In a similar way, MCP standardizes how to integrate additional context
  10546. and tools into the ecosystem of AI applications.
  10547. ## Key Details
  10548. ### Base Protocol
  10549. * [JSON-RPC](https://www.jsonrpc.org/) message format
  10550. * Stateful connections
  10551. * Server and client capability negotiation
  10552. ### Features
  10553. Servers offer any of the following features to clients:
  10554. * **Resources**: Context and data, for the user or the AI model to use
  10555. * **Prompts**: Templated messages and workflows for users
  10556. * **Tools**: Functions for the AI model to execute
  10557. Clients may offer the following feature to servers:
  10558. * **Sampling**: Server-initiated agentic behaviors and recursive LLM interactions
  10559. ### Additional Utilities
  10560. * Configuration
  10561. * Progress tracking
  10562. * Cancellation
  10563. * Error reporting
  10564. * Logging
  10565. ## Security and Trust & Safety
  10566. The Model Context Protocol enables powerful capabilities through arbitrary data access
  10567. and code execution paths. With this power comes important security and trust
  10568. considerations that all implementors must carefully address.
  10569. ### Key Principles
  10570. 1. **User Consent and Control**
  10571. * Users must explicitly consent to and understand all data access and operations
  10572. * Users must retain control over what data is shared and what actions are taken
  10573. * Implementors should provide clear UIs for reviewing and authorizing activities
  10574. 2. **Data Privacy**
  10575. * Hosts must obtain explicit user consent before exposing user data to servers
  10576. * Hosts must not transmit resource data elsewhere without user consent
  10577. * User data should be protected with appropriate access controls
  10578. 3. **Tool Safety**
  10579. * Tools represent arbitrary code execution and must be treated with appropriate
  10580. caution.
  10581. * In particular, descriptions of tool behavior such as annotations should be
  10582. considered untrusted, unless obtained from a trusted server.
  10583. * Hosts must obtain explicit user consent before invoking any tool
  10584. * Users should understand what each tool does before authorizing its use
  10585. 4. **LLM Sampling Controls**
  10586. * Users must explicitly approve any LLM sampling requests
  10587. * Users should control:
  10588. * Whether sampling occurs at all
  10589. * The actual prompt that will be sent
  10590. * What results the server can see
  10591. * The protocol intentionally limits server visibility into prompts
  10592. ### Implementation Guidelines
  10593. While MCP itself cannot enforce these security principles at the protocol level,
  10594. implementors **SHOULD**:
  10595. 1. Build robust consent and authorization flows into their applications
  10596. 2. Provide clear documentation of security implications
  10597. 3. Implement appropriate access controls and data protections
  10598. 4. Follow security best practices in their integrations
  10599. 5. Consider privacy implications in their feature designs
  10600. ## Learn More
  10601. Explore the detailed specification for each protocol component:
  10602. <CardGroup cols={5}>
  10603. <Card title="Architecture" icon="sitemap" href="/specification/2025-03-26/architecture" />
  10604. <Card title="Base Protocol" icon="code" href="/specification/2025-03-26/basic" />
  10605. <Card title="Server Features" icon="server" href="/specification/2025-03-26/server" />
  10606. <Card title="Client Features" icon="user" href="/specification/2025-03-26/client" />
  10607. <Card title="Contributing" icon="pencil" href="/specification/contributing" />
  10608. </CardGroup>
  10609. # Overview
  10610. Source: https://modelcontextprotocol.io/specification/2025-03-26/server/index
  10611. <Info>**Protocol Revision**: 2025-03-26</Info>
  10612. Servers provide the fundamental building blocks for adding context to language models via
  10613. MCP. These primitives enable rich interactions between clients, servers, and language
  10614. models:
  10615. * **Prompts**: Pre-defined templates or instructions that guide language model
  10616. interactions
  10617. * **Resources**: Structured data or content that provides additional context to the model
  10618. * **Tools**: Executable functions that allow models to perform actions or retrieve
  10619. information
  10620. Each primitive can be summarized in the following control hierarchy:
  10621. | Primitive | Control | Description | Example |
  10622. | --------- | ---------------------- | -------------------------------------------------- | ------------------------------- |
  10623. | Prompts | User-controlled | Interactive templates invoked by user choice | Slash commands, menu options |
  10624. | Resources | Application-controlled | Contextual data attached and managed by the client | File contents, git history |
  10625. | Tools | Model-controlled | Functions exposed to the LLM to take actions | API POST requests, file writing |
  10626. Explore these key primitives in more detail below:
  10627. <CardGroup cols={3}>
  10628. <Card title="Prompts" icon="message" href="/specification/2025-03-26/server/prompts" />
  10629. <Card title="Resources" icon="file-lines" href="/specification/2025-03-26/server/resources" />
  10630. <Card title="Tools" icon="wrench" href="/specification/2025-03-26/server/tools" />
  10631. </CardGroup>
  10632. # Prompts
  10633. Source: https://modelcontextprotocol.io/specification/2025-03-26/server/prompts
  10634. <Info>**Protocol Revision**: 2025-03-26</Info>
  10635. The Model Context Protocol (MCP) provides a standardized way for servers to expose prompt
  10636. templates to clients. Prompts allow servers to provide structured messages and
  10637. instructions for interacting with language models. Clients can discover available
  10638. prompts, retrieve their contents, and provide arguments to customize them.
  10639. ## User Interaction Model
  10640. Prompts are designed to be **user-controlled**, meaning they are exposed from servers to
  10641. clients with the intention of the user being able to explicitly select them for use.
  10642. Typically, prompts would be triggered through user-initiated commands in the user
  10643. interface, which allows users to naturally discover and invoke available prompts.
  10644. For example, as slash commands:
  10645. ![Example of prompt exposed as slash command](https://mintlify.s3.us-west-1.amazonaws.com/mcp/specification/2025-03-26/server/slash-command.png)
  10646. However, implementors are free to expose prompts through any interface pattern that suits
  10647. their needs—the protocol itself does not mandate any specific user interaction
  10648. model.
  10649. ## Capabilities
  10650. Servers that support prompts **MUST** declare the `prompts` capability during
  10651. [initialization](/specification/2025-03-26/basic/lifecycle#initialization):
  10652. ```json
  10653. {
  10654. "capabilities": {
  10655. "prompts": {
  10656. "listChanged": true
  10657. }
  10658. }
  10659. }
  10660. ```
  10661. `listChanged` indicates whether the server will emit notifications when the list of
  10662. available prompts changes.
  10663. ## Protocol Messages
  10664. ### Listing Prompts
  10665. To retrieve available prompts, clients send a `prompts/list` request. This operation
  10666. supports [pagination](/specification/2025-03-26/server/utilities/pagination).
  10667. **Request:**
  10668. ```json
  10669. {
  10670. "jsonrpc": "2.0",
  10671. "id": 1,
  10672. "method": "prompts/list",
  10673. "params": {
  10674. "cursor": "optional-cursor-value"
  10675. }
  10676. }
  10677. ```
  10678. **Response:**
  10679. ```json
  10680. {
  10681. "jsonrpc": "2.0",
  10682. "id": 1,
  10683. "result": {
  10684. "prompts": [
  10685. {
  10686. "name": "code_review",
  10687. "description": "Asks the LLM to analyze code quality and suggest improvements",
  10688. "arguments": [
  10689. {
  10690. "name": "code",
  10691. "description": "The code to review",
  10692. "required": true
  10693. }
  10694. ]
  10695. }
  10696. ],
  10697. "nextCursor": "next-page-cursor"
  10698. }
  10699. }
  10700. ```
  10701. ### Getting a Prompt
  10702. To retrieve a specific prompt, clients send a `prompts/get` request. Arguments may be
  10703. auto-completed through [the completion API](/specification/2025-03-26/server/utilities/completion).
  10704. **Request:**
  10705. ```json
  10706. {
  10707. "jsonrpc": "2.0",
  10708. "id": 2,
  10709. "method": "prompts/get",
  10710. "params": {
  10711. "name": "code_review",
  10712. "arguments": {
  10713. "code": "def hello():\n print('world')"
  10714. }
  10715. }
  10716. }
  10717. ```
  10718. **Response:**
  10719. ```json
  10720. {
  10721. "jsonrpc": "2.0",
  10722. "id": 2,
  10723. "result": {
  10724. "description": "Code review prompt",
  10725. "messages": [
  10726. {
  10727. "role": "user",
  10728. "content": {
  10729. "type": "text",
  10730. "text": "Please review this Python code:\ndef hello():\n print('world')"
  10731. }
  10732. }
  10733. ]
  10734. }
  10735. }
  10736. ```
  10737. ### List Changed Notification
  10738. When the list of available prompts changes, servers that declared the `listChanged`
  10739. capability **SHOULD** send a notification:
  10740. ```json
  10741. {
  10742. "jsonrpc": "2.0",
  10743. "method": "notifications/prompts/list_changed"
  10744. }
  10745. ```
  10746. ## Message Flow
  10747. ```mermaid
  10748. sequenceDiagram
  10749. participant Client
  10750. participant Server
  10751. Note over Client,Server: Discovery
  10752. Client->>Server: prompts/list
  10753. Server-->>Client: List of prompts
  10754. Note over Client,Server: Usage
  10755. Client->>Server: prompts/get
  10756. Server-->>Client: Prompt content
  10757. opt listChanged
  10758. Note over Client,Server: Changes
  10759. Server--)Client: prompts/list_changed
  10760. Client->>Server: prompts/list
  10761. Server-->>Client: Updated prompts
  10762. end
  10763. ```
  10764. ## Data Types
  10765. ### Prompt
  10766. A prompt definition includes:
  10767. * `name`: Unique identifier for the prompt
  10768. * `description`: Optional human-readable description
  10769. * `arguments`: Optional list of arguments for customization
  10770. ### PromptMessage
  10771. Messages in a prompt can contain:
  10772. * `role`: Either "user" or "assistant" to indicate the speaker
  10773. * `content`: One of the following content types:
  10774. #### Text Content
  10775. Text content represents plain text messages:
  10776. ```json
  10777. {
  10778. "type": "text",
  10779. "text": "The text content of the message"
  10780. }
  10781. ```
  10782. This is the most common content type used for natural language interactions.
  10783. #### Image Content
  10784. Image content allows including visual information in messages:
  10785. ```json
  10786. {
  10787. "type": "image",
  10788. "data": "base64-encoded-image-data",
  10789. "mimeType": "image/png"
  10790. }
  10791. ```
  10792. The image data **MUST** be base64-encoded and include a valid MIME type. This enables
  10793. multi-modal interactions where visual context is important.
  10794. #### Audio Content
  10795. Audio content allows including audio information in messages:
  10796. ```json
  10797. {
  10798. "type": "audio",
  10799. "data": "base64-encoded-audio-data",
  10800. "mimeType": "audio/wav"
  10801. }
  10802. ```
  10803. The audio data MUST be base64-encoded and include a valid MIME type. This enables
  10804. multi-modal interactions where audio context is important.
  10805. #### Embedded Resources
  10806. Embedded resources allow referencing server-side resources directly in messages:
  10807. ```json
  10808. {
  10809. "type": "resource",
  10810. "resource": {
  10811. "uri": "resource://example",
  10812. "mimeType": "text/plain",
  10813. "text": "Resource content"
  10814. }
  10815. }
  10816. ```
  10817. Resources can contain either text or binary (blob) data and **MUST** include:
  10818. * A valid resource URI
  10819. * The appropriate MIME type
  10820. * Either text content or base64-encoded blob data
  10821. Embedded resources enable prompts to seamlessly incorporate server-managed content like
  10822. documentation, code samples, or other reference materials directly into the conversation
  10823. flow.
  10824. ## Error Handling
  10825. Servers **SHOULD** return standard JSON-RPC errors for common failure cases:
  10826. * Invalid prompt name: `-32602` (Invalid params)
  10827. * Missing required arguments: `-32602` (Invalid params)
  10828. * Internal errors: `-32603` (Internal error)
  10829. ## Implementation Considerations
  10830. 1. Servers **SHOULD** validate prompt arguments before processing
  10831. 2. Clients **SHOULD** handle pagination for large prompt lists
  10832. 3. Both parties **SHOULD** respect capability negotiation
  10833. ## Security
  10834. Implementations **MUST** carefully validate all prompt inputs and outputs to prevent
  10835. injection attacks or unauthorized access to resources.
  10836. # Resources
  10837. Source: https://modelcontextprotocol.io/specification/2025-03-26/server/resources
  10838. <Info>**Protocol Revision**: 2025-03-26</Info>
  10839. The Model Context Protocol (MCP) provides a standardized way for servers to expose
  10840. resources to clients. Resources allow servers to share data that provides context to
  10841. language models, such as files, database schemas, or application-specific information.
  10842. Each resource is uniquely identified by a
  10843. [URI](https://datatracker.ietf.org/doc/html/rfc3986).
  10844. ## User Interaction Model
  10845. Resources in MCP are designed to be **application-driven**, with host applications
  10846. determining how to incorporate context based on their needs.
  10847. For example, applications could:
  10848. * Expose resources through UI elements for explicit selection, in a tree or list view
  10849. * Allow the user to search through and filter available resources
  10850. * Implement automatic context inclusion, based on heuristics or the AI model's selection
  10851. ![Example of resource context picker](https://mintlify.s3.us-west-1.amazonaws.com/mcp/specification/2025-03-26/server/resource-picker.png)
  10852. However, implementations are free to expose resources through any interface pattern that
  10853. suits their needs—the protocol itself does not mandate any specific user
  10854. interaction model.
  10855. ## Capabilities
  10856. Servers that support resources **MUST** declare the `resources` capability:
  10857. ```json
  10858. {
  10859. "capabilities": {
  10860. "resources": {
  10861. "subscribe": true,
  10862. "listChanged": true
  10863. }
  10864. }
  10865. }
  10866. ```
  10867. The capability supports two optional features:
  10868. * `subscribe`: whether the client can subscribe to be notified of changes to individual
  10869. resources.
  10870. * `listChanged`: whether the server will emit notifications when the list of available
  10871. resources changes.
  10872. Both `subscribe` and `listChanged` are optional—servers can support neither,
  10873. either, or both:
  10874. ```json
  10875. {
  10876. "capabilities": {
  10877. "resources": {} // Neither feature supported
  10878. }
  10879. }
  10880. ```
  10881. ```json
  10882. {
  10883. "capabilities": {
  10884. "resources": {
  10885. "subscribe": true // Only subscriptions supported
  10886. }
  10887. }
  10888. }
  10889. ```
  10890. ```json
  10891. {
  10892. "capabilities": {
  10893. "resources": {
  10894. "listChanged": true // Only list change notifications supported
  10895. }
  10896. }
  10897. }
  10898. ```
  10899. ## Protocol Messages
  10900. ### Listing Resources
  10901. To discover available resources, clients send a `resources/list` request. This operation
  10902. supports [pagination](/specification/2025-03-26/server/utilities/pagination).
  10903. **Request:**
  10904. ```json
  10905. {
  10906. "jsonrpc": "2.0",
  10907. "id": 1,
  10908. "method": "resources/list",
  10909. "params": {
  10910. "cursor": "optional-cursor-value"
  10911. }
  10912. }
  10913. ```
  10914. **Response:**
  10915. ```json
  10916. {
  10917. "jsonrpc": "2.0",
  10918. "id": 1,
  10919. "result": {
  10920. "resources": [
  10921. {
  10922. "uri": "file:///project/src/main.rs",
  10923. "name": "main.rs",
  10924. "description": "Primary application entry point",
  10925. "mimeType": "text/x-rust"
  10926. }
  10927. ],
  10928. "nextCursor": "next-page-cursor"
  10929. }
  10930. }
  10931. ```
  10932. ### Reading Resources
  10933. To retrieve resource contents, clients send a `resources/read` request:
  10934. **Request:**
  10935. ```json
  10936. {
  10937. "jsonrpc": "2.0",
  10938. "id": 2,
  10939. "method": "resources/read",
  10940. "params": {
  10941. "uri": "file:///project/src/main.rs"
  10942. }
  10943. }
  10944. ```
  10945. **Response:**
  10946. ```json
  10947. {
  10948. "jsonrpc": "2.0",
  10949. "id": 2,
  10950. "result": {
  10951. "contents": [
  10952. {
  10953. "uri": "file:///project/src/main.rs",
  10954. "mimeType": "text/x-rust",
  10955. "text": "fn main() {\n println!(\"Hello world!\");\n}"
  10956. }
  10957. ]
  10958. }
  10959. }
  10960. ```
  10961. ### Resource Templates
  10962. Resource templates allow servers to expose parameterized resources using
  10963. [URI templates](https://datatracker.ietf.org/doc/html/rfc6570). Arguments may be
  10964. auto-completed through [the completion API](/specification/2025-03-26/server/utilities/completion).
  10965. **Request:**
  10966. ```json
  10967. {
  10968. "jsonrpc": "2.0",
  10969. "id": 3,
  10970. "method": "resources/templates/list"
  10971. }
  10972. ```
  10973. **Response:**
  10974. ```json
  10975. {
  10976. "jsonrpc": "2.0",
  10977. "id": 3,
  10978. "result": {
  10979. "resourceTemplates": [
  10980. {
  10981. "uriTemplate": "file:///{path}",
  10982. "name": "Project Files",
  10983. "description": "Access files in the project directory",
  10984. "mimeType": "application/octet-stream"
  10985. }
  10986. ]
  10987. }
  10988. }
  10989. ```
  10990. ### List Changed Notification
  10991. When the list of available resources changes, servers that declared the `listChanged`
  10992. capability **SHOULD** send a notification:
  10993. ```json
  10994. {
  10995. "jsonrpc": "2.0",
  10996. "method": "notifications/resources/list_changed"
  10997. }
  10998. ```
  10999. ### Subscriptions
  11000. The protocol supports optional subscriptions to resource changes. Clients can subscribe
  11001. to specific resources and receive notifications when they change:
  11002. **Subscribe Request:**
  11003. ```json
  11004. {
  11005. "jsonrpc": "2.0",
  11006. "id": 4,
  11007. "method": "resources/subscribe",
  11008. "params": {
  11009. "uri": "file:///project/src/main.rs"
  11010. }
  11011. }
  11012. ```
  11013. **Update Notification:**
  11014. ```json
  11015. {
  11016. "jsonrpc": "2.0",
  11017. "method": "notifications/resources/updated",
  11018. "params": {
  11019. "uri": "file:///project/src/main.rs"
  11020. }
  11021. }
  11022. ```
  11023. ## Message Flow
  11024. ```mermaid
  11025. sequenceDiagram
  11026. participant Client
  11027. participant Server
  11028. Note over Client,Server: Resource Discovery
  11029. Client->>Server: resources/list
  11030. Server-->>Client: List of resources
  11031. Note over Client,Server: Resource Access
  11032. Client->>Server: resources/read
  11033. Server-->>Client: Resource contents
  11034. Note over Client,Server: Subscriptions
  11035. Client->>Server: resources/subscribe
  11036. Server-->>Client: Subscription confirmed
  11037. Note over Client,Server: Updates
  11038. Server--)Client: notifications/resources/updated
  11039. Client->>Server: resources/read
  11040. Server-->>Client: Updated contents
  11041. ```
  11042. ## Data Types
  11043. ### Resource
  11044. A resource definition includes:
  11045. * `uri`: Unique identifier for the resource
  11046. * `name`: Human-readable name
  11047. * `description`: Optional description
  11048. * `mimeType`: Optional MIME type
  11049. * `size`: Optional size in bytes
  11050. ### Resource Contents
  11051. Resources can contain either text or binary data:
  11052. #### Text Content
  11053. ```json
  11054. {
  11055. "uri": "file:///example.txt",
  11056. "mimeType": "text/plain",
  11057. "text": "Resource content"
  11058. }
  11059. ```
  11060. #### Binary Content
  11061. ```json
  11062. {
  11063. "uri": "file:///example.png",
  11064. "mimeType": "image/png",
  11065. "blob": "base64-encoded-data"
  11066. }
  11067. ```
  11068. ## Common URI Schemes
  11069. The protocol defines several standard URI schemes. This list not
  11070. exhaustive—implementations are always free to use additional, custom URI schemes.
  11071. ### https\://
  11072. Used to represent a resource available on the web.
  11073. Servers **SHOULD** use this scheme only when the client is able to fetch and load the
  11074. resource directly from the web on its own—that is, it doesn’t need to read the resource
  11075. via the MCP server.
  11076. For other use cases, servers **SHOULD** prefer to use another URI scheme, or define a
  11077. custom one, even if the server will itself be downloading resource contents over the
  11078. internet.
  11079. ### file://
  11080. Used to identify resources that behave like a filesystem. However, the resources do not
  11081. need to map to an actual physical filesystem.
  11082. MCP servers **MAY** identify file:// resources with an
  11083. [XDG MIME type](https://specifications.freedesktop.org/shared-mime-info-spec/0.14/ar01s02.html#id-1.3.14),
  11084. like `inode/directory`, to represent non-regular files (such as directories) that don’t
  11085. otherwise have a standard MIME type.
  11086. ### git://
  11087. Git version control integration.
  11088. ## Error Handling
  11089. Servers **SHOULD** return standard JSON-RPC errors for common failure cases:
  11090. * Resource not found: `-32002`
  11091. * Internal errors: `-32603`
  11092. Example error:
  11093. ```json
  11094. {
  11095. "jsonrpc": "2.0",
  11096. "id": 5,
  11097. "error": {
  11098. "code": -32002,
  11099. "message": "Resource not found",
  11100. "data": {
  11101. "uri": "file:///nonexistent.txt"
  11102. }
  11103. }
  11104. }
  11105. ```
  11106. ## Security Considerations
  11107. 1. Servers **MUST** validate all resource URIs
  11108. 2. Access controls **SHOULD** be implemented for sensitive resources
  11109. 3. Binary data **MUST** be properly encoded
  11110. 4. Resource permissions **SHOULD** be checked before operations
  11111. # Tools
  11112. Source: https://modelcontextprotocol.io/specification/2025-03-26/server/tools
  11113. <Info>**Protocol Revision**: 2025-03-26</Info>
  11114. The Model Context Protocol (MCP) allows servers to expose tools that can be invoked by
  11115. language models. Tools enable models to interact with external systems, such as querying
  11116. databases, calling APIs, or performing computations. Each tool is uniquely identified by
  11117. a name and includes metadata describing its schema.
  11118. ## User Interaction Model
  11119. Tools in MCP are designed to be **model-controlled**, meaning that the language model can
  11120. discover and invoke tools automatically based on its contextual understanding and the
  11121. user's prompts.
  11122. However, implementations are free to expose tools through any interface pattern that
  11123. suits their needs—the protocol itself does not mandate any specific user
  11124. interaction model.
  11125. <Warning>
  11126. For trust & safety and security, there **SHOULD** always
  11127. be a human in the loop with the ability to deny tool invocations.
  11128. Applications **SHOULD**:
  11129. * Provide UI that makes clear which tools are being exposed to the AI model
  11130. * Insert clear visual indicators when tools are invoked
  11131. * Present confirmation prompts to the user for operations, to ensure a human is in the
  11132. loop
  11133. </Warning>
  11134. ## Capabilities
  11135. Servers that support tools **MUST** declare the `tools` capability:
  11136. ```json
  11137. {
  11138. "capabilities": {
  11139. "tools": {
  11140. "listChanged": true
  11141. }
  11142. }
  11143. }
  11144. ```
  11145. `listChanged` indicates whether the server will emit notifications when the list of
  11146. available tools changes.
  11147. ## Protocol Messages
  11148. ### Listing Tools
  11149. To discover available tools, clients send a `tools/list` request. This operation supports
  11150. [pagination](/specification/2025-03-26/server/utilities/pagination).
  11151. **Request:**
  11152. ```json
  11153. {
  11154. "jsonrpc": "2.0",
  11155. "id": 1,
  11156. "method": "tools/list",
  11157. "params": {
  11158. "cursor": "optional-cursor-value"
  11159. }
  11160. }
  11161. ```
  11162. **Response:**
  11163. ```json
  11164. {
  11165. "jsonrpc": "2.0",
  11166. "id": 1,
  11167. "result": {
  11168. "tools": [
  11169. {
  11170. "name": "get_weather",
  11171. "description": "Get current weather information for a location",
  11172. "inputSchema": {
  11173. "type": "object",
  11174. "properties": {
  11175. "location": {
  11176. "type": "string",
  11177. "description": "City name or zip code"
  11178. }
  11179. },
  11180. "required": ["location"]
  11181. }
  11182. }
  11183. ],
  11184. "nextCursor": "next-page-cursor"
  11185. }
  11186. }
  11187. ```
  11188. ### Calling Tools
  11189. To invoke a tool, clients send a `tools/call` request:
  11190. **Request:**
  11191. ```json
  11192. {
  11193. "jsonrpc": "2.0",
  11194. "id": 2,
  11195. "method": "tools/call",
  11196. "params": {
  11197. "name": "get_weather",
  11198. "arguments": {
  11199. "location": "New York"
  11200. }
  11201. }
  11202. }
  11203. ```
  11204. **Response:**
  11205. ```json
  11206. {
  11207. "jsonrpc": "2.0",
  11208. "id": 2,
  11209. "result": {
  11210. "content": [
  11211. {
  11212. "type": "text",
  11213. "text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy"
  11214. }
  11215. ],
  11216. "isError": false
  11217. }
  11218. }
  11219. ```
  11220. ### List Changed Notification
  11221. When the list of available tools changes, servers that declared the `listChanged`
  11222. capability **SHOULD** send a notification:
  11223. ```json
  11224. {
  11225. "jsonrpc": "2.0",
  11226. "method": "notifications/tools/list_changed"
  11227. }
  11228. ```
  11229. ## Message Flow
  11230. ```mermaid
  11231. sequenceDiagram
  11232. participant LLM
  11233. participant Client
  11234. participant Server
  11235. Note over Client,Server: Discovery
  11236. Client->>Server: tools/list
  11237. Server-->>Client: List of tools
  11238. Note over Client,LLM: Tool Selection
  11239. LLM->>Client: Select tool to use
  11240. Note over Client,Server: Invocation
  11241. Client->>Server: tools/call
  11242. Server-->>Client: Tool result
  11243. Client->>LLM: Process result
  11244. Note over Client,Server: Updates
  11245. Server--)Client: tools/list_changed
  11246. Client->>Server: tools/list
  11247. Server-->>Client: Updated tools
  11248. ```
  11249. ## Data Types
  11250. ### Tool
  11251. A tool definition includes:
  11252. * `name`: Unique identifier for the tool
  11253. * `description`: Human-readable description of functionality
  11254. * `inputSchema`: JSON Schema defining expected parameters
  11255. * `annotations`: optional properties describing tool behavior
  11256. <Warning>
  11257. For trust & safety and security, clients **MUST** consider
  11258. tool annotations to be untrusted unless they come from trusted servers.
  11259. </Warning>
  11260. ### Tool Result
  11261. Tool results can contain multiple content items of different types:
  11262. #### Text Content
  11263. ```json
  11264. {
  11265. "type": "text",
  11266. "text": "Tool result text"
  11267. }
  11268. ```
  11269. #### Image Content
  11270. ```json
  11271. {
  11272. "type": "image",
  11273. "data": "base64-encoded-data",
  11274. "mimeType": "image/png"
  11275. }
  11276. ```
  11277. #### Audio Content
  11278. ```json
  11279. {
  11280. "type": "audio",
  11281. "data": "base64-encoded-audio-data",
  11282. "mimeType": "audio/wav"
  11283. }
  11284. ```
  11285. #### Embedded Resources
  11286. [Resources](/specification/2025-03-26/server/resources) **MAY** be embedded, to provide additional context
  11287. or data, behind a URI that can be subscribed to or fetched again by the client later:
  11288. ```json
  11289. {
  11290. "type": "resource",
  11291. "resource": {
  11292. "uri": "resource://example",
  11293. "mimeType": "text/plain",
  11294. "text": "Resource content"
  11295. }
  11296. }
  11297. ```
  11298. ## Error Handling
  11299. Tools use two error reporting mechanisms:
  11300. 1. **Protocol Errors**: Standard JSON-RPC errors for issues like:
  11301. * Unknown tools
  11302. * Invalid arguments
  11303. * Server errors
  11304. 2. **Tool Execution Errors**: Reported in tool results with `isError: true`:
  11305. * API failures
  11306. * Invalid input data
  11307. * Business logic errors
  11308. Example protocol error:
  11309. ```json
  11310. {
  11311. "jsonrpc": "2.0",
  11312. "id": 3,
  11313. "error": {
  11314. "code": -32602,
  11315. "message": "Unknown tool: invalid_tool_name"
  11316. }
  11317. }
  11318. ```
  11319. Example tool execution error:
  11320. ```json
  11321. {
  11322. "jsonrpc": "2.0",
  11323. "id": 4,
  11324. "result": {
  11325. "content": [
  11326. {
  11327. "type": "text",
  11328. "text": "Failed to fetch weather data: API rate limit exceeded"
  11329. }
  11330. ],
  11331. "isError": true
  11332. }
  11333. }
  11334. ```
  11335. ## Security Considerations
  11336. 1. Servers **MUST**:
  11337. * Validate all tool inputs
  11338. * Implement proper access controls
  11339. * Rate limit tool invocations
  11340. * Sanitize tool outputs
  11341. 2. Clients **SHOULD**:
  11342. * Prompt for user confirmation on sensitive operations
  11343. * Show tool inputs to the user before calling the server, to avoid malicious or
  11344. accidental data exfiltration
  11345. * Validate tool results before passing to LLM
  11346. * Implement timeouts for tool calls
  11347. * Log tool usage for audit purposes
  11348. # Completion
  11349. Source: https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/completion
  11350. <Info>**Protocol Revision**: 2025-03-26</Info>
  11351. The Model Context Protocol (MCP) provides a standardized way for servers to offer
  11352. argument autocompletion suggestions for prompts and resource URIs. This enables rich,
  11353. IDE-like experiences where users receive contextual suggestions while entering argument
  11354. values.
  11355. ## User Interaction Model
  11356. Completion in MCP is designed to support interactive user experiences similar to IDE code
  11357. completion.
  11358. For example, applications may show completion suggestions in a dropdown or popup menu as
  11359. users type, with the ability to filter and select from available options.
  11360. However, implementations are free to expose completion through any interface pattern that
  11361. suits their needs—the protocol itself does not mandate any specific user
  11362. interaction model.
  11363. ## Capabilities
  11364. Servers that support completions **MUST** declare the `completions` capability:
  11365. ```json
  11366. {
  11367. "capabilities": {
  11368. "completions": {}
  11369. }
  11370. }
  11371. ```
  11372. ## Protocol Messages
  11373. ### Requesting Completions
  11374. To get completion suggestions, clients send a `completion/complete` request specifying
  11375. what is being completed through a reference type:
  11376. **Request:**
  11377. ```json
  11378. {
  11379. "jsonrpc": "2.0",
  11380. "id": 1,
  11381. "method": "completion/complete",
  11382. "params": {
  11383. "ref": {
  11384. "type": "ref/prompt",
  11385. "name": "code_review"
  11386. },
  11387. "argument": {
  11388. "name": "language",
  11389. "value": "py"
  11390. }
  11391. }
  11392. }
  11393. ```
  11394. **Response:**
  11395. ```json
  11396. {
  11397. "jsonrpc": "2.0",
  11398. "id": 1,
  11399. "result": {
  11400. "completion": {
  11401. "values": ["python", "pytorch", "pyside"],
  11402. "total": 10,
  11403. "hasMore": true
  11404. }
  11405. }
  11406. }
  11407. ```
  11408. ### Reference Types
  11409. The protocol supports two types of completion references:
  11410. | Type | Description | Example |
  11411. | -------------- | --------------------------- | --------------------------------------------------- |
  11412. | `ref/prompt` | References a prompt by name | `{"type": "ref/prompt", "name": "code_review"}` |
  11413. | `ref/resource` | References a resource URI | `{"type": "ref/resource", "uri": "file:///{path}"}` |
  11414. ### Completion Results
  11415. Servers return an array of completion values ranked by relevance, with:
  11416. * Maximum 100 items per response
  11417. * Optional total number of available matches
  11418. * Boolean indicating if additional results exist
  11419. ## Message Flow
  11420. ```mermaid
  11421. sequenceDiagram
  11422. participant Client
  11423. participant Server
  11424. Note over Client: User types argument
  11425. Client->>Server: completion/complete
  11426. Server-->>Client: Completion suggestions
  11427. Note over Client: User continues typing
  11428. Client->>Server: completion/complete
  11429. Server-->>Client: Refined suggestions
  11430. ```
  11431. ## Data Types
  11432. ### CompleteRequest
  11433. * `ref`: A `PromptReference` or `ResourceReference`
  11434. * `argument`: Object containing:
  11435. * `name`: Argument name
  11436. * `value`: Current value
  11437. ### CompleteResult
  11438. * `completion`: Object containing:
  11439. * `values`: Array of suggestions (max 100)
  11440. * `total`: Optional total matches
  11441. * `hasMore`: Additional results flag
  11442. ## Error Handling
  11443. Servers **SHOULD** return standard JSON-RPC errors for common failure cases:
  11444. * Method not found: `-32601` (Capability not supported)
  11445. * Invalid prompt name: `-32602` (Invalid params)
  11446. * Missing required arguments: `-32602` (Invalid params)
  11447. * Internal errors: `-32603` (Internal error)
  11448. ## Implementation Considerations
  11449. 1. Servers **SHOULD**:
  11450. * Return suggestions sorted by relevance
  11451. * Implement fuzzy matching where appropriate
  11452. * Rate limit completion requests
  11453. * Validate all inputs
  11454. 2. Clients **SHOULD**:
  11455. * Debounce rapid completion requests
  11456. * Cache completion results where appropriate
  11457. * Handle missing or partial results gracefully
  11458. ## Security
  11459. Implementations **MUST**:
  11460. * Validate all completion inputs
  11461. * Implement appropriate rate limiting
  11462. * Control access to sensitive suggestions
  11463. * Prevent completion-based information disclosure
  11464. # Logging
  11465. Source: https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/logging
  11466. <Info>**Protocol Revision**: 2025-03-26</Info>
  11467. The Model Context Protocol (MCP) provides a standardized way for servers to send
  11468. structured log messages to clients. Clients can control logging verbosity by setting
  11469. minimum log levels, with servers sending notifications containing severity levels,
  11470. optional logger names, and arbitrary JSON-serializable data.
  11471. ## User Interaction Model
  11472. Implementations are free to expose logging through any interface pattern that suits their
  11473. needs—the protocol itself does not mandate any specific user interaction model.
  11474. ## Capabilities
  11475. Servers that emit log message notifications **MUST** declare the `logging` capability:
  11476. ```json
  11477. {
  11478. "capabilities": {
  11479. "logging": {}
  11480. }
  11481. }
  11482. ```
  11483. ## Log Levels
  11484. The protocol follows the standard syslog severity levels specified in
  11485. [RFC 5424](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1):
  11486. | Level | Description | Example Use Case |
  11487. | --------- | -------------------------------- | -------------------------- |
  11488. | debug | Detailed debugging information | Function entry/exit points |
  11489. | info | General informational messages | Operation progress updates |
  11490. | notice | Normal but significant events | Configuration changes |
  11491. | warning | Warning conditions | Deprecated feature usage |
  11492. | error | Error conditions | Operation failures |
  11493. | critical | Critical conditions | System component failures |
  11494. | alert | Action must be taken immediately | Data corruption detected |
  11495. | emergency | System is unusable | Complete system failure |
  11496. ## Protocol Messages
  11497. ### Setting Log Level
  11498. To configure the minimum log level, clients **MAY** send a `logging/setLevel` request:
  11499. **Request:**
  11500. ```json
  11501. {
  11502. "jsonrpc": "2.0",
  11503. "id": 1,
  11504. "method": "logging/setLevel",
  11505. "params": {
  11506. "level": "info"
  11507. }
  11508. }
  11509. ```
  11510. ### Log Message Notifications
  11511. Servers send log messages using `notifications/message` notifications:
  11512. ```json
  11513. {
  11514. "jsonrpc": "2.0",
  11515. "method": "notifications/message",
  11516. "params": {
  11517. "level": "error",
  11518. "logger": "database",
  11519. "data": {
  11520. "error": "Connection failed",
  11521. "details": {
  11522. "host": "localhost",
  11523. "port": 5432
  11524. }
  11525. }
  11526. }
  11527. }
  11528. ```
  11529. ## Message Flow
  11530. ```mermaid
  11531. sequenceDiagram
  11532. participant Client
  11533. participant Server
  11534. Note over Client,Server: Configure Logging
  11535. Client->>Server: logging/setLevel (info)
  11536. Server-->>Client: Empty Result
  11537. Note over Client,Server: Server Activity
  11538. Server--)Client: notifications/message (info)
  11539. Server--)Client: notifications/message (warning)
  11540. Server--)Client: notifications/message (error)
  11541. Note over Client,Server: Level Change
  11542. Client->>Server: logging/setLevel (error)
  11543. Server-->>Client: Empty Result
  11544. Note over Server: Only sends error level<br/>and above
  11545. ```
  11546. ## Error Handling
  11547. Servers **SHOULD** return standard JSON-RPC errors for common failure cases:
  11548. * Invalid log level: `-32602` (Invalid params)
  11549. * Configuration errors: `-32603` (Internal error)
  11550. ## Implementation Considerations
  11551. 1. Servers **SHOULD**:
  11552. * Rate limit log messages
  11553. * Include relevant context in data field
  11554. * Use consistent logger names
  11555. * Remove sensitive information
  11556. 2. Clients **MAY**:
  11557. * Present log messages in the UI
  11558. * Implement log filtering/search
  11559. * Display severity visually
  11560. * Persist log messages
  11561. ## Security
  11562. 1. Log messages **MUST NOT** contain:
  11563. * Credentials or secrets
  11564. * Personal identifying information
  11565. * Internal system details that could aid attacks
  11566. 2. Implementations **SHOULD**:
  11567. * Rate limit messages
  11568. * Validate all data fields
  11569. * Control log access
  11570. * Monitor for sensitive content
  11571. # Pagination
  11572. Source: https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/pagination
  11573. <Info>**Protocol Revision**: 2025-03-26</Info>
  11574. The Model Context Protocol (MCP) supports paginating list operations that may return
  11575. large result sets. Pagination allows servers to yield results in smaller chunks rather
  11576. than all at once.
  11577. Pagination is especially important when connecting to external services over the
  11578. internet, but also useful for local integrations to avoid performance issues with large
  11579. data sets.
  11580. ## Pagination Model
  11581. Pagination in MCP uses an opaque cursor-based approach, instead of numbered pages.
  11582. * The **cursor** is an opaque string token, representing a position in the result set
  11583. * **Page size** is determined by the server, and clients **MUST NOT** assume a fixed page
  11584. size
  11585. ## Response Format
  11586. Pagination starts when the server sends a **response** that includes:
  11587. * The current page of results
  11588. * An optional `nextCursor` field if more results exist
  11589. ```json
  11590. {
  11591. "jsonrpc": "2.0",
  11592. "id": "123",
  11593. "result": {
  11594. "resources": [...],
  11595. "nextCursor": "eyJwYWdlIjogM30="
  11596. }
  11597. }
  11598. ```
  11599. ## Request Format
  11600. After receiving a cursor, the client can *continue* paginating by issuing a request
  11601. including that cursor:
  11602. ```json
  11603. {
  11604. "jsonrpc": "2.0",
  11605. "method": "resources/list",
  11606. "params": {
  11607. "cursor": "eyJwYWdlIjogMn0="
  11608. }
  11609. }
  11610. ```
  11611. ## Pagination Flow
  11612. ```mermaid
  11613. sequenceDiagram
  11614. participant Client
  11615. participant Server
  11616. Client->>Server: List Request (no cursor)
  11617. loop Pagination Loop
  11618. Server-->>Client: Page of results + nextCursor
  11619. Client->>Server: List Request (with cursor)
  11620. end
  11621. ```
  11622. ## Operations Supporting Pagination
  11623. The following MCP operations support pagination:
  11624. * `resources/list` - List available resources
  11625. * `resources/templates/list` - List resource templates
  11626. * `prompts/list` - List available prompts
  11627. * `tools/list` - List available tools
  11628. ## Implementation Guidelines
  11629. 1. Servers **SHOULD**:
  11630. * Provide stable cursors
  11631. * Handle invalid cursors gracefully
  11632. 2. Clients **SHOULD**:
  11633. * Treat a missing `nextCursor` as the end of results
  11634. * Support both paginated and non-paginated flows
  11635. 3. Clients **MUST** treat cursors as opaque tokens:
  11636. * Don't make assumptions about cursor format
  11637. * Don't attempt to parse or modify cursors
  11638. * Don't persist cursors across sessions
  11639. ## Error Handling
  11640. Invalid cursors **SHOULD** result in an error with code -32602 (Invalid params).
  11641. # Contributions
  11642. Source: https://modelcontextprotocol.io/specification/contributing
  11643. We welcome contributions from the community! Please review our
  11644. [contributing guidelines](https://github.com/modelcontextprotocol/specification/blob/main/CONTRIBUTING.md)
  11645. for details on how to submit changes.
  11646. All contributors must adhere to our
  11647. [Code of Conduct](https://github.com/modelcontextprotocol/specification/blob/main/CODE_OF_CONDUCT.md).
  11648. For questions and discussions, please use
  11649. [GitHub Discussions](https://github.com/modelcontextprotocol/specification/discussions).
  11650. # Architecture
  11651. Source: https://modelcontextprotocol.io/specification/draft/architecture/index
  11652. <div id="enable-section-numbers" />
  11653. The Model Context Protocol (MCP) follows a client-host-server architecture where each
  11654. host can run multiple client instances. This architecture enables users to integrate AI
  11655. capabilities across applications while maintaining clear security boundaries and
  11656. isolating concerns. Built on JSON-RPC, MCP provides a stateful session protocol focused
  11657. on context exchange and sampling coordination between clients and servers.
  11658. ## Core Components
  11659. ```mermaid
  11660. graph LR
  11661. subgraph "Application Host Process"
  11662. H[Host]
  11663. C1[Client 1]
  11664. C2[Client 2]
  11665. C3[Client 3]
  11666. H --> C1
  11667. H --> C2
  11668. H --> C3
  11669. end
  11670. subgraph "Local machine"
  11671. S1[Server 1<br>Files & Git]
  11672. S2[Server 2<br>Database]
  11673. R1[("Local<br>Resource A")]
  11674. R2[("Local<br>Resource B")]
  11675. C1 --> S1
  11676. C2 --> S2
  11677. S1 <--> R1
  11678. S2 <--> R2
  11679. end
  11680. subgraph "Internet"
  11681. S3[Server 3<br>External APIs]
  11682. R3[("Remote<br>Resource C")]
  11683. C3 --> S3
  11684. S3 <--> R3
  11685. end
  11686. ```
  11687. ### Host
  11688. The host process acts as the container and coordinator:
  11689. * Creates and manages multiple client instances
  11690. * Controls client connection permissions and lifecycle
  11691. * Enforces security policies and consent requirements
  11692. * Handles user authorization decisions
  11693. * Coordinates AI/LLM integration and sampling
  11694. * Manages context aggregation across clients
  11695. ### Clients
  11696. Each client is created by the host and maintains an isolated server connection:
  11697. * Establishes one stateful session per server
  11698. * Handles protocol negotiation and capability exchange
  11699. * Routes protocol messages bidirectionally
  11700. * Manages subscriptions and notifications
  11701. * Maintains security boundaries between servers
  11702. A host application creates and manages multiple clients, with each client having a 1:1
  11703. relationship with a particular server.
  11704. ### Servers
  11705. Servers provide specialized context and capabilities:
  11706. * Expose resources, tools and prompts via MCP primitives
  11707. * Operate independently with focused responsibilities
  11708. * Request sampling through client interfaces
  11709. * Must respect security constraints
  11710. * Can be local processes or remote services
  11711. ## Design Principles
  11712. MCP is built on several key design principles that inform its architecture and
  11713. implementation:
  11714. 1. **Servers should be extremely easy to build**
  11715. * Host applications handle complex orchestration responsibilities
  11716. * Servers focus on specific, well-defined capabilities
  11717. * Simple interfaces minimize implementation overhead
  11718. * Clear separation enables maintainable code
  11719. 2. **Servers should be highly composable**
  11720. * Each server provides focused functionality in isolation
  11721. * Multiple servers can be combined seamlessly
  11722. * Shared protocol enables interoperability
  11723. * Modular design supports extensibility
  11724. 3. **Servers should not be able to read the whole conversation, nor "see into" other
  11725. servers**
  11726. * Servers receive only necessary contextual information
  11727. * Full conversation history stays with the host
  11728. * Each server connection maintains isolation
  11729. * Cross-server interactions are controlled by the host
  11730. * Host process enforces security boundaries
  11731. 4. **Features can be added to servers and clients progressively**
  11732. * Core protocol provides minimal required functionality
  11733. * Additional capabilities can be negotiated as needed
  11734. * Servers and clients evolve independently
  11735. * Protocol designed for future extensibility
  11736. * Backwards compatibility is maintained
  11737. ## Capability Negotiation
  11738. The Model Context Protocol uses a capability-based negotiation system where clients and
  11739. servers explicitly declare their supported features during initialization. Capabilities
  11740. determine which protocol features and primitives are available during a session.
  11741. * Servers declare capabilities like resource subscriptions, tool support, and prompt
  11742. templates
  11743. * Clients declare capabilities like sampling support and notification handling
  11744. * Both parties must respect declared capabilities throughout the session
  11745. * Additional capabilities can be negotiated through extensions to the protocol
  11746. ```mermaid
  11747. sequenceDiagram
  11748. participant Host
  11749. participant Client
  11750. participant Server
  11751. Host->>+Client: Initialize client
  11752. Client->>+Server: Initialize session with capabilities
  11753. Server-->>Client: Respond with supported capabilities
  11754. Note over Host,Server: Active Session with Negotiated Features
  11755. loop Client Requests
  11756. Host->>Client: User- or model-initiated action
  11757. Client->>Server: Request (tools/resources)
  11758. Server-->>Client: Response
  11759. Client-->>Host: Update UI or respond to model
  11760. end
  11761. loop Server Requests
  11762. Server->>Client: Request (sampling)
  11763. Client->>Host: Forward to AI
  11764. Host-->>Client: AI response
  11765. Client-->>Server: Response
  11766. end
  11767. loop Notifications
  11768. Server--)Client: Resource updates
  11769. Client--)Server: Status changes
  11770. end
  11771. Host->>Client: Terminate
  11772. Client->>-Server: End session
  11773. deactivate Server
  11774. ```
  11775. Each capability unlocks specific protocol features for use during the session. For
  11776. example:
  11777. * Implemented [server features](/specification/draft/server) must be advertised in the
  11778. server's capabilities
  11779. * Emitting resource subscription notifications requires the server to declare
  11780. subscription support
  11781. * Tool invocation requires the server to declare tool capabilities
  11782. * [Sampling](/specification/draft/client) requires the client to declare support in its
  11783. capabilities
  11784. This capability negotiation ensures clients and servers have a clear understanding of
  11785. supported functionality while maintaining protocol extensibility.
  11786. # Authorization
  11787. Source: https://modelcontextprotocol.io/specification/draft/basic/authorization
  11788. <div id="enable-section-numbers" />
  11789. <Info>**Protocol Revision**: draft</Info>
  11790. ## Introduction
  11791. ### Purpose and Scope
  11792. The Model Context Protocol provides authorization capabilities at the transport level,
  11793. enabling MCP clients to make requests to restricted MCP servers on behalf of resource
  11794. owners. This specification defines the authorization flow for HTTP-based transports.
  11795. ### Protocol Requirements
  11796. Authorization is **OPTIONAL** for MCP implementations. When supported:
  11797. * Implementations using an HTTP-based transport **SHOULD** conform to this specification.
  11798. * Implementations using an STDIO transport **SHOULD NOT** follow this specification, and
  11799. instead retrieve credentials from the environment.
  11800. * Implementations using alternative transports **MUST** follow established security best
  11801. practices for their protocol.
  11802. ### Standards Compliance
  11803. This authorization mechanism is based on established specifications listed below, but
  11804. implements a selected subset of their features to ensure security and interoperability
  11805. while maintaining simplicity:
  11806. * OAuth 2.1 IETF DRAFT ([draft-ietf-oauth-v2-1-12](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12))
  11807. * OAuth 2.0 Authorization Server Metadata
  11808. ([RFC8414](https://datatracker.ietf.org/doc/html/rfc8414))
  11809. * OAuth 2.0 Dynamic Client Registration Protocol
  11810. ([RFC7591](https://datatracker.ietf.org/doc/html/rfc7591))
  11811. * OAuth 2.0 Protected Resource Metadata ([RFC9728](https://datatracker.ietf.org/doc/html/rfc9728))
  11812. ## Authorization Flow
  11813. ### Overview
  11814. 1. MCP authorization servers **MUST** implement OAuth 2.1 with appropriate security
  11815. measures for both confidential and public clients.
  11816. 2. MCP authorization servers and MCP clients **SHOULD** support the OAuth 2.0 Dynamic Client Registration
  11817. Protocol ([RFC7591](https://datatracker.ietf.org/doc/html/rfc7591)).
  11818. 3. MCP servers **MUST** implement OAuth 2.0 Protected Resource Metadata ([RFC9728](https://datatracker.ietf.org/doc/html/rfc9728)).
  11819. MCP clients **MUST** use OAuth 2.0 Protected Resource Metadata for authorization server discovery.
  11820. 4. MCP authorization servers **MUST** provide OAuth 2.0 Authorization
  11821. Server Metadata ([RFC8414](https://datatracker.ietf.org/doc/html/rfc8414)).
  11822. MCP clients **MUST** use the OAuth 2.0 Authorization Server Metadata.
  11823. ### Roles
  11824. A protected MCP server acts as an [OAuth 2.1 resource server](https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-12.html#name-roles),
  11825. capable of accepting and responding to protected resource requests using access tokens.
  11826. An MCP client acts as an [OAuth 2.1 client](https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-12.html#name-roles),
  11827. making protected resource requests on behalf of a resource owner.
  11828. The authorization server is responsible for interacting with the user (if necessary) and issuing access tokens for use at the MCP server.
  11829. The implementation details of the authorization server are beyond the scope of this specification. It may be hosted with the
  11830. resource server or a separate entity. The [Authorization Server Discovery section](#authorization-server-discovery)
  11831. specifies how an MCP server indicates the location of its corresponding authorization server to a client.
  11832. ### Authorization Server Discovery
  11833. This section describes the mechanisms by which MCP servers advertise their associated
  11834. authorization servers to MCP clients, as well as the discovery process through which MCP
  11835. clients can determine authorization server endpoints and supported capabilities.
  11836. #### Authorization Server Location
  11837. MCP servers **MUST** implement the OAuth 2.0 Protected Resource Metadata ([RFC9728](https://datatracker.ietf.org/doc/html/rfc9728))
  11838. specification to indicate the locations of authorization servers. The Protected Resource Metadata document returned by the MCP server **MUST** include
  11839. the `authorization_servers` field containing at least one authorization server.
  11840. The specific use of `authorization_servers` is beyond the scope of this specification; implementers should consult
  11841. OAuth 2.0 Protected Resource Metadata ([RFC9728](https://datatracker.ietf.org/doc/html/rfc9728)) for
  11842. guidance on implementation details.
  11843. Implementors should note that Protected Resource Metadata documents can define multiple authorization servers. The responsibility for selecting which authorization server to use lies with the MCP client, following the guidelines specified in
  11844. [RFC9728 Section 7.6 "Authorization Servers"](https://datatracker.ietf.org/doc/html/rfc9728#name-authorization-servers).
  11845. MCP servers **MUST** use the HTTP header `WWW-Authenticate` when returning a *401 Unauthorized* to indicate the location of the resource server metadata URL
  11846. as described in [RFC9728 Section 5.1 "WWW-Authenticate Response"](https://datatracker.ietf.org/doc/html/rfc9728#name-www-authenticate-response).
  11847. MCP clients **MUST** be able to parse `WWW-Authenticate` headers and respond appropriately to `HTTP 401 Unauthorized` responses from the MCP server.
  11848. #### Server Metadata Discovery
  11849. MCP clients **MUST** follow the OAuth 2.0 Authorization Server Metadata [RFC8414](https://datatracker.ietf.org/doc/html/rfc8414)
  11850. specification to obtain the information required to interact with the authorization server.
  11851. #### Sequence Diagram
  11852. The following diagram outlines an example flow:
  11853. ```mermaid
  11854. sequenceDiagram
  11855. participant C as Client
  11856. participant M as MCP Server (Resource Server)
  11857. participant A as Authorization Server
  11858. C->>M: MCP request without token
  11859. M-->>C: HTTP 401 Unauthorized with WWW-Authenticate header
  11860. Note over C: Extract resource_metadata<br />from WWW-Authenticate
  11861. C->>M: GET /.well-known/oauth-protected-resource
  11862. M-->>C: Resource metadata with authorization server URL
  11863. Note over C: Validate RS metadata,<br />build AS metadata URL
  11864. C->>A: GET /.well-known/oauth-authorization-server
  11865. A-->>C: Authorization server metadata
  11866. Note over C,A: OAuth 2.1 authorization flow happens here
  11867. C->>A: Token request
  11868. A-->>C: Access token
  11869. C->>M: MCP request with access token
  11870. M-->>C: MCP response
  11871. Note over C,M: MCP communication continues with valid token
  11872. ```
  11873. ### Dynamic Client Registration
  11874. MCP clients and authorization servers **SHOULD** support the
  11875. OAuth 2.0 Dynamic Client Registration Protocol [RFC7591](https://datatracker.ietf.org/doc/html/rfc7591)
  11876. to allow MCP clients to obtain OAuth client IDs without user interaction. This provides a
  11877. standardized way for clients to automatically register with new authorization servers, which is crucial
  11878. for MCP because:
  11879. * Clients may not know all possible MCP servers and their authorization servers in advance.
  11880. * Manual registration would create friction for users.
  11881. * It enables seamless connection to new MCP servers and their authorization servers.
  11882. * Authorization servers can implement their own registration policies.
  11883. Any MCP authorization servers that *do not* support Dynamic Client Registration need to provide
  11884. alternative ways to obtain a client ID (and, if applicable, client credentials). For one of
  11885. these authorization servers, MCP clients will have to either:
  11886. 1. Hardcode a client ID (and, if applicable, client credentials) specifically for the MCP client to use when
  11887. interacting with that authorization server, or
  11888. 2. Present a UI to users that allows them to enter these details, after registering an
  11889. OAuth client themselves (e.g., through a configuration interface hosted by the
  11890. server).
  11891. ### Authorization Flow Steps
  11892. The complete Authorization flow proceeds as follows:
  11893. ```mermaid
  11894. sequenceDiagram
  11895. participant B as User-Agent (Browser)
  11896. participant C as Client
  11897. participant M as MCP Server (Resource Server)
  11898. participant A as Authorization Server
  11899. C->>M: MCP request without token
  11900. M->>C: HTTP 401 Unauthorized with WWW-Authenticate header
  11901. Note over C: Extract resource_metadata URL from WWW-Authenticate
  11902. C->>M: Request Protected Resource Metadata
  11903. M->>C: Return metadata
  11904. Note over C: Parse metadata and extract authorization server(s)<br/>Client determines AS to use
  11905. C->>A: GET /.well-known/oauth-authorization-server
  11906. A->>C: Authorization server metadata response
  11907. alt Dynamic client registration
  11908. C->>A: POST /register
  11909. A->>C: Client Credentials
  11910. end
  11911. Note over C: Generate PKCE parameters
  11912. C->>B: Open browser with authorization URL + code_challenge
  11913. B->>A: Authorization request
  11914. Note over A: User authorizes
  11915. A->>B: Redirect to callback with authorization code
  11916. B->>C: Authorization code callback
  11917. C->>A: Token request + code_verifier
  11918. A->>C: Access token (+ refresh token)
  11919. C->>M: MCP request with access token
  11920. M-->>C: MCP response
  11921. Note over C,M: MCP communication continues with valid token
  11922. ```
  11923. ### Access Token Usage
  11924. #### Token Requirements
  11925. Access token handling when making requests to MCP servers **MUST** conform to the requirements defined in
  11926. [OAuth 2.1 Section 5 "Resource Requests"](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5).
  11927. Specifically:
  11928. 1. MCP client **MUST** use the Authorization request header field defined in
  11929. [OAuth 2.1 Section 5.1.1](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.1.1):
  11930. ```
  11931. Authorization: Bearer <access-token>
  11932. ```
  11933. Note that authorization **MUST** be included in every HTTP request from client to server,
  11934. even if they are part of the same logical session.
  11935. 2. Access tokens **MUST NOT** be included in the URI query string
  11936. Example request:
  11937. ```http
  11938. GET /v1/contexts HTTP/1.1
  11939. Host: mcp.example.com
  11940. Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
  11941. ```
  11942. #### Token Handling
  11943. MCP servers, acting in their role as an OAuth 2.1 resource server, **MUST** validate access tokens as described in
  11944. [OAuth 2.1 Section 5.2](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.2).
  11945. If validation fails, servers **MUST** respond according to
  11946. [OAuth 2.1 Section 5.3](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.3)
  11947. error handling requirements. Invalid or expired tokens **MUST** receive a HTTP 401
  11948. response.
  11949. MCP clients **MUST NOT** send tokens to the MCP server other than ones issued by the MCP server's authorization server.
  11950. MCP authorization servers **MUST** only accept tokens that are valid for use with their
  11951. own resources.
  11952. MCP servers **MUST NOT** accept or transit any other tokens.
  11953. ### Error Handling
  11954. Servers **MUST** return appropriate HTTP status codes for authorization errors:
  11955. | Status Code | Description | Usage |
  11956. | ----------- | ------------ | ------------------------------------------ |
  11957. | 401 | Unauthorized | Authorization required or token invalid |
  11958. | 403 | Forbidden | Invalid scopes or insufficient permissions |
  11959. | 400 | Bad Request | Malformed authorization request |
  11960. ## Security Considerations
  11961. Implementations **MUST** follow OAuth 2.1 security best practices as laid out in [OAuth 2.1 Section 7. "Security Considerations"](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#name-security-considerations).
  11962. ### Token Theft
  11963. Attackers who obtain tokens stored by the client, or tokens cached or logged on the server can access protected resources with
  11964. requests that appear legitimate to resource servers.
  11965. Clients and servers **MUST** implement secure token storage and follow OAuth best practices,
  11966. as outlined in [OAuth 2.1, Section 7.1](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-7.1).
  11967. MCP authorization servers SHOULD issue short-lived access tokens to reduce the impact of leaked tokens.
  11968. For public clients, MCP authorization servers **MUST** rotate refresh tokens as described in [OAuth 2.1 Section 4.3.1 "Refresh Token Grant"](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-4.3.1).
  11969. ### Communication Security
  11970. Implementations **MUST** follow [OAuth 2.1 Section 1.5 "Communication Security"](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-1.5).
  11971. Specifically:
  11972. 1. All authorization server endpoints **MUST** be served over HTTPS.
  11973. 2. All redirect URIs **MUST** be either `localhost` or use HTTPS.
  11974. ### Authorization Code Protection
  11975. An attacker who has gained access to an authorization code contained in an authorization response can try to redeem the authorization code for an access token or otherwise make use of the authorization code.
  11976. (Further described in [OAuth 2.1 Section 7.5](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-7.5))
  11977. To mitigate this, MCP clients **MUST** implement PKCE according to [OAuth 2.1 Section 7.5.2](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-7.5.2).
  11978. PKCE helps prevent authorization code interception and injection attacks by requiring clients to create a secret verifier-challenge pair, ensuring that only the original requestor can exchange an authorization code for tokens.
  11979. ### Open Redirection
  11980. An attacker may craft malicious redirect URIs to direct users to phishing sites.
  11981. MCP clients **MUST** have redirect URIs registered with the authorization server.
  11982. Authorization servers **MUST** validate exact redirect URIs against pre-registered values to prevent redirection attacks.
  11983. MCP clients **SHOULD** use and verify state parameters in the authorization code flow
  11984. and discard any results that do not include or have a mis-match with the original state.
  11985. Authorization servers **MUST** take precautions to prevent redirecting user agents to untrusted URI's, following suggestions laid out in [OAuth 2.1 Section 7.12.2](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-7.12.2)
  11986. Authorization servers **SHOULD** only automatically redirect the user agent if it trusts the redirection URI. If the URI is not trusted, the authorization server MAY inform the user and rely on the user to make the correct decision.
  11987. ### Confused Deputy Problem
  11988. Attackers can exploit MCP servers acting as intermediaries to third-party APIs, leading to [confused deputy vulnerabilities](/specification/draft/basic/security_best_practices#confused-deputy-problem).
  11989. By using stolen authorization codes, they can obtain access tokens without user consent.
  11990. MCP proxy servers using static client IDs **MUST** obtain user consent for each dynamically
  11991. registered client before forwarding to third-party authorization servers (which may require additional consent).
  11992. ### Access Token Privilege Restriction
  11993. An attacker can gain unauthorized access or otherwise compromise a MCP server if the server accepts tokens issued for other resources.
  11994. This vulnerability has two critical dimensions:
  11995. 1. **Audience validation failures.** When an MCP server doesn't verify that tokens were specifically intended for it (for example, via the audience claim, as mentioned in [RFC9068](https://www.rfc-editor.org/rfc/rfc9068.html)), it may accept tokens originally issued for other services. This breaks a fundamental OAuth security boundary, allowing attackers to reuse legitimate tokens across different services than intended.
  11996. 2. **Token passthrough.** If the MCP server not only accepts tokens with incorrect audiences but also forwards these unmodified tokens to downstream services, it can potentially cause the ["confused deputy" problem](#confused-deputy-problem), where the downstream API may incorrectly trust the token as if it came from the MCP server or assume the token was validated by the upstream API. See the [Token Passthrough section](/specification/draft/basic/security_best_practices#token-passthrough) of the Security Best Practices guide for additional details.
  11997. MCP servers **MUST** validate access tokens before processing the request, ensuring the access token is issued specifically for the MCP server, and take all necessary steps to ensure no data is returned to unauthorized parties.
  11998. A MCP server **MUST** follow the guidelines in [OAuth 2.1 - Section 5.2](https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-12.html#section-5.2) to validate inbound tokens.
  11999. MCP servers **MUST** only accept tokens specifically intended for themselves.
  12000. If the MCP server makes requests to upstream APIs, it may act as an OAuth client to them. The access token used at the upstream API is a seperate token, issued by the upstream authorization server. The MCP server **MUST NOT** pass through the token it received from the MCP client.
  12001. If the authorization server supports the `resource` parameter, it is recommended that implementers follow [RFC 8707](https://www.rfc-editor.org/rfc/rfc8707.html) to prevent token misuse.
  12002. # Overview
  12003. Source: https://modelcontextprotocol.io/specification/draft/basic/index
  12004. <Info>**Protocol Revision**: draft</Info>
  12005. The Model Context Protocol consists of several key components that work together:
  12006. * **Base Protocol**: Core JSON-RPC message types
  12007. * **Lifecycle Management**: Connection initialization, capability negotiation, and
  12008. session control
  12009. * **Server Features**: Resources, prompts, and tools exposed by servers
  12010. * **Client Features**: Sampling and root directory lists provided by clients
  12011. * **Utilities**: Cross-cutting concerns like logging and argument completion
  12012. All implementations **MUST** support the base protocol and lifecycle management
  12013. components. Other components **MAY** be implemented based on the specific needs of the
  12014. application.
  12015. These protocol layers establish clear separation of concerns while enabling rich
  12016. interactions between clients and servers. The modular design allows implementations to
  12017. support exactly the features they need.
  12018. ## Messages
  12019. All messages between MCP clients and servers **MUST** follow the
  12020. [JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines
  12021. these types of messages:
  12022. ### Requests
  12023. Requests are sent from the client to the server or vice versa, to initiate an operation.
  12024. ```typescript
  12025. {
  12026. jsonrpc: "2.0";
  12027. id: string | number;
  12028. method: string;
  12029. params?: {
  12030. [key: string]: unknown;
  12031. };
  12032. }
  12033. ```
  12034. * Requests **MUST** include a string or integer ID.
  12035. * Unlike base JSON-RPC, the ID **MUST NOT** be `null`.
  12036. * The request ID **MUST NOT** have been previously used by the requestor within the same
  12037. session.
  12038. ### Responses
  12039. Responses are sent in reply to requests, containing the result or error of the operation.
  12040. ```typescript
  12041. {
  12042. jsonrpc: "2.0";
  12043. id: string | number;
  12044. result?: {
  12045. [key: string]: unknown;
  12046. }
  12047. error?: {
  12048. code: number;
  12049. message: string;
  12050. data?: unknown;
  12051. }
  12052. }
  12053. ```
  12054. * Responses **MUST** include the same ID as the request they correspond to.
  12055. * **Responses** are further sub-categorized as either **successful results** or
  12056. **errors**. Either a `result` or an `error` **MUST** be set. A response **MUST NOT**
  12057. set both.
  12058. * Results **MAY** follow any JSON object structure, while errors **MUST** include an
  12059. error code and message at minimum.
  12060. * Error codes **MUST** be integers.
  12061. ### Notifications
  12062. Notifications are sent from the client to the server or vice versa, as a one-way message.
  12063. The receiver **MUST NOT** send a response.
  12064. ```typescript
  12065. {
  12066. jsonrpc: "2.0";
  12067. method: string;
  12068. params?: {
  12069. [key: string]: unknown;
  12070. };
  12071. }
  12072. ```
  12073. * Notifications **MUST NOT** include an ID.
  12074. ## Auth
  12075. MCP provides an [Authorization](/specification/draft/basic/authorization) framework for use with HTTP.
  12076. Implementations using an HTTP-based transport **SHOULD** conform to this specification,
  12077. whereas implementations using STDIO transport **SHOULD NOT** follow this specification,
  12078. and instead retrieve credentials from the environment.
  12079. Additionally, clients and servers **MAY** negotiate their own custom authentication and
  12080. authorization strategies.
  12081. For further discussions and contributions to the evolution of MCP’s auth mechanisms, join
  12082. us in
  12083. [GitHub Discussions](https://github.com/modelcontextprotocol/specification/discussions)
  12084. to help shape the future of the protocol!
  12085. ## Schema
  12086. The full specification of the protocol is defined as a
  12087. [TypeScript schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/draft/schema.ts).
  12088. This is the source of truth for all protocol messages and structures.
  12089. There is also a
  12090. [JSON Schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/draft/schema.json),
  12091. which is automatically generated from the TypeScript source of truth, for use with
  12092. various automated tooling.
  12093. # Lifecycle
  12094. Source: https://modelcontextprotocol.io/specification/draft/basic/lifecycle
  12095. <div id="enable-section-numbers" />
  12096. <Info>**Protocol Revision**: draft</Info>
  12097. The Model Context Protocol (MCP) defines a rigorous lifecycle for client-server
  12098. connections that ensures proper capability negotiation and state management.
  12099. 1. **Initialization**: Capability negotiation and protocol version agreement
  12100. 2. **Operation**: Normal protocol communication
  12101. 3. **Shutdown**: Graceful termination of the connection
  12102. ```mermaid
  12103. sequenceDiagram
  12104. participant Client
  12105. participant Server
  12106. Note over Client,Server: Initialization Phase
  12107. activate Client
  12108. Client->>+Server: initialize request
  12109. Server-->>Client: initialize response
  12110. Client--)Server: initialized notification
  12111. Note over Client,Server: Operation Phase
  12112. rect rgb(200, 220, 250)
  12113. note over Client,Server: Normal protocol operations
  12114. end
  12115. Note over Client,Server: Shutdown
  12116. Client--)-Server: Disconnect
  12117. deactivate Server
  12118. Note over Client,Server: Connection closed
  12119. ```
  12120. ## Lifecycle Phases
  12121. ### Initialization
  12122. The initialization phase **MUST** be the first interaction between client and server.
  12123. During this phase, the client and server:
  12124. * Establish protocol version compatibility
  12125. * Exchange and negotiate capabilities
  12126. * Share implementation details
  12127. The client **MUST** initiate this phase by sending an `initialize` request containing:
  12128. * Protocol version supported
  12129. * Client capabilities
  12130. * Client implementation information
  12131. ```json
  12132. {
  12133. "jsonrpc": "2.0",
  12134. "id": 1,
  12135. "method": "initialize",
  12136. "params": {
  12137. "protocolVersion": "2024-11-05",
  12138. "capabilities": {
  12139. "roots": {
  12140. "listChanged": true
  12141. },
  12142. "sampling": {},
  12143. "elicitation": {}
  12144. },
  12145. "clientInfo": {
  12146. "name": "ExampleClient",
  12147. "version": "1.0.0"
  12148. }
  12149. }
  12150. }
  12151. ```
  12152. The server **MUST** respond with its own capabilities and information:
  12153. ```json
  12154. {
  12155. "jsonrpc": "2.0",
  12156. "id": 1,
  12157. "result": {
  12158. "protocolVersion": "2024-11-05",
  12159. "capabilities": {
  12160. "logging": {},
  12161. "prompts": {
  12162. "listChanged": true
  12163. },
  12164. "resources": {
  12165. "subscribe": true,
  12166. "listChanged": true
  12167. },
  12168. "tools": {
  12169. "listChanged": true
  12170. }
  12171. },
  12172. "serverInfo": {
  12173. "name": "ExampleServer",
  12174. "version": "1.0.0"
  12175. },
  12176. "instructions": "Optional instructions for the client"
  12177. }
  12178. }
  12179. ```
  12180. After successful initialization, the client **MUST** send an `initialized` notification
  12181. to indicate it is ready to begin normal operations:
  12182. ```json
  12183. {
  12184. "jsonrpc": "2.0",
  12185. "method": "notifications/initialized"
  12186. }
  12187. ```
  12188. * The client **SHOULD NOT** send requests other than
  12189. [pings](/specification/draft/basic/utilities/ping) before the server has responded to the
  12190. `initialize` request.
  12191. * The server **SHOULD NOT** send requests other than
  12192. [pings](/specification/draft/basic/utilities/ping) and
  12193. [logging](/specification/draft/server/utilities/logging) before receiving the `initialized`
  12194. notification.
  12195. #### Version Negotiation
  12196. In the `initialize` request, the client **MUST** send a protocol version it supports.
  12197. This **SHOULD** be the *latest* version supported by the client.
  12198. If the server supports the requested protocol version, it **MUST** respond with the same
  12199. version. Otherwise, the server **MUST** respond with another protocol version it
  12200. supports. This **SHOULD** be the *latest* version supported by the server.
  12201. If the client does not support the version in the server's response, it **SHOULD**
  12202. disconnect.
  12203. <Note>
  12204. If using HTTP, the client **MUST** include the `MCP-Protocol-Version: <protocol-version>` HTTP header on all subsequent requests to the MCP
  12205. server.
  12206. For details, see [the Protocol Version Header section in Transports](/specification/draft/basic/transports#protocol-version-header).
  12207. </Note>
  12208. #### Capability Negotiation
  12209. Client and server capabilities establish which optional protocol features will be
  12210. available during the session.
  12211. Key capabilities include:
  12212. | Category | Capability | Description |
  12213. | -------- | -------------- | ------------------------------------------------------------------------------------ |
  12214. | Client | `roots` | Ability to provide filesystem [roots](/specification/draft/client/roots) |
  12215. | Client | `sampling` | Support for LLM [sampling](/specification/draft/client/sampling) requests |
  12216. | Client | `elicitation` | Support for server [elicitation](/specification/draft/client/elicitation) requests |
  12217. | Client | `experimental` | Describes support for non-standard experimental features |
  12218. | Server | `prompts` | Offers [prompt templates](/specification/draft/server/prompts) |
  12219. | Server | `resources` | Provides readable [resources](/specification/draft/server/resources) |
  12220. | Server | `tools` | Exposes callable [tools](/specification/draft/server/tools) |
  12221. | Server | `logging` | Emits structured [log messages](/specification/draft/server/utilities/logging) |
  12222. | Server | `completions` | Supports argument [autocompletion](/specification/draft/server/utilities/completion) |
  12223. | Server | `experimental` | Describes support for non-standard experimental features |
  12224. Capability objects can describe sub-capabilities like:
  12225. * `listChanged`: Support for list change notifications (for prompts, resources, and
  12226. tools)
  12227. * `subscribe`: Support for subscribing to individual items' changes (resources only)
  12228. ### Operation
  12229. During the operation phase, the client and server exchange messages according to the
  12230. negotiated capabilities.
  12231. Both parties **SHOULD**:
  12232. * Respect the negotiated protocol version
  12233. * Only use capabilities that were successfully negotiated
  12234. ### Shutdown
  12235. During the shutdown phase, one side (usually the client) cleanly terminates the protocol
  12236. connection. No specific shutdown messages are defined—instead, the underlying transport
  12237. mechanism should be used to signal connection termination:
  12238. #### stdio
  12239. For the stdio [transport](/specification/draft/basic/transports), the client **SHOULD** initiate
  12240. shutdown by:
  12241. 1. First, closing the input stream to the child process (the server)
  12242. 2. Waiting for the server to exit, or sending `SIGTERM` if the server does not exit
  12243. within a reasonable time
  12244. 3. Sending `SIGKILL` if the server does not exit within a reasonable time after `SIGTERM`
  12245. The server **MAY** initiate shutdown by closing its output stream to the client and
  12246. exiting.
  12247. #### HTTP
  12248. For HTTP [transports](/specification/draft/basic/transports), shutdown is indicated by closing the
  12249. associated HTTP connection(s).
  12250. ## Timeouts
  12251. Implementations **SHOULD** establish timeouts for all sent requests, to prevent hung
  12252. connections and resource exhaustion. When the request has not received a success or error
  12253. response within the timeout period, the sender **SHOULD** issue a [cancellation
  12254. notification](/specification/draft/basic/utilities/cancellation) for that request and stop waiting for
  12255. a response.
  12256. SDKs and other middleware **SHOULD** allow these timeouts to be configured on a
  12257. per-request basis.
  12258. Implementations **MAY** choose to reset the timeout clock when receiving a [progress
  12259. notification](/specification/draft/basic/utilities/progress) corresponding to the request, as this
  12260. implies that work is actually happening. However, implementations **SHOULD** always
  12261. enforce a maximum timeout, regardless of progress notifications, to limit the impact of a
  12262. misbehaving client or server.
  12263. ## Error Handling
  12264. Implementations **SHOULD** be prepared to handle these error cases:
  12265. * Protocol version mismatch
  12266. * Failure to negotiate required capabilities
  12267. * Request [timeouts](#timeouts)
  12268. Example initialization error:
  12269. ```json
  12270. {
  12271. "jsonrpc": "2.0",
  12272. "id": 1,
  12273. "error": {
  12274. "code": -32602,
  12275. "message": "Unsupported protocol version",
  12276. "data": {
  12277. "supported": ["2024-11-05"],
  12278. "requested": "1.0.0"
  12279. }
  12280. }
  12281. }
  12282. ```
  12283. # Security Best Practices
  12284. Source: https://modelcontextprotocol.io/specification/draft/basic/security_best_practices
  12285. <div id="enable-section-numbers" />
  12286. ## Introduction
  12287. ### Purpose and Scope
  12288. This document provides security considerations for the Model Context Protocol (MCP), complementing the MCP Authorization specification. This document identifies security risks, attack vectors, and best practices specific to MCP implementations.
  12289. The primary audience for this document includes developers implementing MCP authorization flows, MCP server operators, and security professionals evaluating MCP-based systems. This document should be read alongside the MCP Authorization specification and [OAuth 2.0 security best practices](https://datatracker.ietf.org/doc/html/rfc9700).
  12290. ## Attacks and Mitigations
  12291. This section gives a detailed description of attacks on MCP implementations, along with potential countermeasures.
  12292. ### Confused Deputy Problem
  12293. Attackers can exploit MCP servers proxying other resource servers, creating "[confused deputy](https://en.wikipedia.org/wiki/Confused_deputy_problem)" vulnerabilities.
  12294. #### Terminology
  12295. **MCP Proxy Server**
  12296. : An MCP server that connects MCP clients to third-party APIs, offering MCP features while delegating operations and acting as a single OAuth client to the third-party API server.
  12297. **Third-Party Authorization Server**
  12298. : Authorization server that protects the third-party API. It may lack dynamic client registration support, requiring MCP proxy to use a static client ID for all requests.
  12299. **Third-Party API**
  12300. : The protected resource server that provides the actual API functionality. Access to this
  12301. API requires tokens issued by the third-party authorization server.
  12302. **Static Client ID**
  12303. : A fixed OAuth 2.0 client identifier used by the MCP proxy server when communicating with
  12304. the third-party authorization server. This Client ID refers to the MCP server acting as a client
  12305. to the Third-Party API. It is the same value for all MCP server to Third-Party API interactions regardless of
  12306. which MCP client initiated the request.
  12307. #### Architecture and Attack Flows
  12308. ##### Normal OAuth proxy usage (preserves user consent)
  12309. ```mermaid
  12310. sequenceDiagram
  12311. participant UA as User-Agent (Browser)
  12312. participant MC as MCP Client
  12313. participant M as MCP Proxy Server
  12314. participant TAS as Third-Party Authorization Server
  12315. Note over UA,M: Initial Auth flow completed
  12316. Note over UA,TAS: Step 1: Legitimate user consent for Third Party Server
  12317. M->>UA: Redirect to third party authorization server
  12318. UA->>TAS: Authorization request (client_id: mcp-proxy)
  12319. TAS->>UA: Authorization consent screen
  12320. Note over UA: Review consent screen
  12321. UA->>TAS: Approve
  12322. TAS->>UA: Set consent cookie for client ID: mcp-proxy
  12323. TAS->>UA: 3P Authorization code + redirect to mcp-proxy-server.com
  12324. UA->>M: 3P Authorization code
  12325. Note over M,TAS: Exchange 3P code for 3P token
  12326. Note over M: Generate MCP authorization code
  12327. M->>UA: Redirect to MCP Client with MCP authorization code
  12328. Note over M,UA: Exchange code for token, etc.
  12329. ```
  12330. ##### Malicious OAuth proxy usage (skips user consent)
  12331. ```mermaid
  12332. sequenceDiagram
  12333. participant UA as User-Agent (Browser)
  12334. participant M as MCP Proxy Server
  12335. participant TAS as Third-Party Authorization Server
  12336. participant A as Attacker
  12337. Note over UA,A: Step 2: Attack (leveraging existing cookie, skipping consent)
  12338. A->>M: Dynamically register malicious client, redirect_uri: attacker.com
  12339. A->>UA: Sends malicious link
  12340. UA->>TAS: Authorization request (client_id: mcp-proxy) + consent cookie
  12341. rect rgba(255, 17, 0, 0.67)
  12342. TAS->>TAS: Cookie present, consent skipped
  12343. end
  12344. TAS->>UA: 3P Authorization code + redirect to mcp-proxy-server.com
  12345. UA->>M: 3P Authorization code
  12346. Note over M,TAS: Exchange 3P code for 3P token
  12347. Note over M: Generate MCP authorization code
  12348. M->>UA: Redirect to attacker.com with MCP Authorization code
  12349. UA->>A: MCP Authorization code delivered to attacker.com
  12350. Note over M,A: Attacker exchanges MCP code for MCP token
  12351. A->>M: Attacker impersonates user to MCP server
  12352. ```
  12353. #### Attack Description
  12354. When an MCP proxy server uses a static client ID to authenticate with a third-party
  12355. authorization server that does not support dynamic client registration, the following
  12356. attack becomes possible:
  12357. 1. A user authenticates normally through the MCP proxy server to access the third-party API
  12358. 2. During this flow, the third-party authorization server sets a cookie on the user agent
  12359. indicating consent for the static client ID
  12360. 3. An attacker later sends the user a malicious link containing a crafted authorization request which contains a malicious redirect URI along with a new dynamically registered client ID
  12361. 4. When the user clicks the link, their browser still has the consent cookie from the previous legitimate request
  12362. 5. The third-party authorization server detects the cookie and skips the consent screen
  12363. 6. The MCP authorization code is redirected to the attacker's server (specified in the crafted redirect\_uri during dynamic client registration)
  12364. 7. The attacker exchanges the stolen authorization code for access tokens for the MCP server without the user's explicit approval
  12365. 8. Attacker now has access to the third-party API as the compromised user
  12366. #### Mitigation
  12367. MCP proxy servers using static client IDs **MUST** obtain user consent for each dynamically
  12368. registered client before forwarding to third-party authorization servers (which may require additional consent).
  12369. ### Token Passthrough
  12370. "Token passthrough" is an anti-pattern where an MCP server accepts tokens from an MCP client without validating that the tokens were properly issued *to the MCP server* and "passing them through" to the downstream API.
  12371. #### Risks
  12372. Token passthrough is explicitly forbidden in the [authorization specification](/specification/draft/basic/authorization) as it introduces a number of security risks, that include:
  12373. * **Security Control Circumvention**
  12374. * The MCP Server or downstream APIs might implement important security controls like rate limiting, request validation, or traffic monitoring, that depend on the token audience or other credential constraints. If clients can obtain and use tokens directly with the downstream APIs without the MCP server validating them properly or ensuring that the tokens are issued for the right service, they bypass these controls.
  12375. * **Accountability and Audit Trail Issues**
  12376. * The MCP Server will be unable to identify or distinguish between MCP Clients when clients are calling with an upstream-issued access token which may be opaque to the MCP Server.
  12377. * The downstream Resource Server’s logs may show requests that appear to come from a different source with a different identity, rather than the MCP server that is actually forwarding the tokens.
  12378. * Both factors make incident investigation, controls, and auditing more difficult.
  12379. * If the MCP Server passes tokens without validating their claims (e.g., roles, privileges, or audience) or other metadata, a malicious actor in possession of a stolen token can use the server as a proxy for data exfiltration.
  12380. * **Trust Boundary Issues**
  12381. * The downstream Resource Server grants trust to specific entities. This trust might include assumptions about origin or client behavior patterns. Breaking this trust boundary could lead to unexpected issues.
  12382. * If the token is accepted by multiple services without proper validation, an attacker compromising one service can use the token to access other connected services.
  12383. * **Future Compatibility Risk**
  12384. * Even if an MCP Server starts as a "pure proxy" today, it might need to add security controls later. Starting with proper token audience separation makes it easier to evolve the security model.
  12385. #### Mitigation
  12386. MCP servers **MUST NOT** accept any tokens that were not explicitly issued for the MCP server.
  12387. # Transports
  12388. Source: https://modelcontextprotocol.io/specification/draft/basic/transports
  12389. <div id="enable-section-numbers" />
  12390. <Info>**Protocol Revision**: draft</Info>
  12391. MCP uses JSON-RPC to encode messages. JSON-RPC messages **MUST** be UTF-8 encoded.
  12392. The protocol currently defines two standard transport mechanisms for client-server
  12393. communication:
  12394. 1. [stdio](#stdio), communication over standard in and standard out
  12395. 2. [Streamable HTTP](#streamable-http)
  12396. Clients **SHOULD** support stdio whenever possible.
  12397. It is also possible for clients and servers to implement
  12398. [custom transports](#custom-transports) in a pluggable fashion.
  12399. ## stdio
  12400. In the **stdio** transport:
  12401. * The client launches the MCP server as a subprocess.
  12402. * The server reads JSON-RPC messages from its standard input (`stdin`) and sends messages
  12403. to its standard output (`stdout`).
  12404. * Messages are individual JSON-RPC requests, notifications, or responses.
  12405. * Messages are delimited by newlines, and **MUST NOT** contain embedded newlines.
  12406. * The server **MAY** write UTF-8 strings to its standard error (`stderr`) for logging
  12407. purposes. Clients **MAY** capture, forward, or ignore this logging.
  12408. * The server **MUST NOT** write anything to its `stdout` that is not a valid MCP message.
  12409. * The client **MUST NOT** write anything to the server's `stdin` that is not a valid MCP
  12410. message.
  12411. ```mermaid
  12412. sequenceDiagram
  12413. participant Client
  12414. participant Server Process
  12415. Client->>+Server Process: Launch subprocess
  12416. loop Message Exchange
  12417. Client->>Server Process: Write to stdin
  12418. Server Process->>Client: Write to stdout
  12419. Server Process--)Client: Optional logs on stderr
  12420. end
  12421. Client->>Server Process: Close stdin, terminate subprocess
  12422. deactivate Server Process
  12423. ```
  12424. ## Streamable HTTP
  12425. <Info>
  12426. This replaces the [HTTP+SSE
  12427. transport](/specification/2024-11-05/basic/transports#http-with-sse) from
  12428. protocol version 2024-11-05. See the [backwards compatibility](#backwards-compatibility)
  12429. guide below.
  12430. </Info>
  12431. In the **Streamable HTTP** transport, the server operates as an independent process that
  12432. can handle multiple client connections. This transport uses HTTP POST and GET requests.
  12433. Server can optionally make use of
  12434. [Server-Sent Events](https://en.wikipedia.org/wiki/Server-sent_events) (SSE) to stream
  12435. multiple server messages. This permits basic MCP servers, as well as more feature-rich
  12436. servers supporting streaming and server-to-client notifications and requests.
  12437. The server **MUST** provide a single HTTP endpoint path (hereafter referred to as the
  12438. **MCP endpoint**) that supports both POST and GET methods. For example, this could be a
  12439. URL like `https://example.com/mcp`.
  12440. #### Security Warning
  12441. When implementing Streamable HTTP transport:
  12442. 1. Servers **MUST** validate the `Origin` header on all incoming connections to prevent DNS rebinding attacks
  12443. 2. When running locally, servers **SHOULD** bind only to localhost (127.0.0.1) rather than all network interfaces (0.0.0.0)
  12444. 3. Servers **SHOULD** implement proper authentication for all connections
  12445. Without these protections, attackers could use DNS rebinding to interact with local MCP servers from remote websites.
  12446. ### Sending Messages to the Server
  12447. Every JSON-RPC message sent from the client **MUST** be a new HTTP POST request to the
  12448. MCP endpoint.
  12449. 1. The client **MUST** use HTTP POST to send JSON-RPC messages to the MCP endpoint.
  12450. 2. The client **MUST** include an `Accept` header, listing both `application/json` and
  12451. `text/event-stream` as supported content types.
  12452. 3. The body of the POST request **MUST** be a single JSON-RPC *request*, *notification*, or *response*.
  12453. 4. If the input is a JSON-RPC *response* or *notification*:
  12454. * If the server accepts the input, the server **MUST** return HTTP status code 202
  12455. Accepted with no body.
  12456. * If the server cannot accept the input, it **MUST** return an HTTP error status code
  12457. (e.g., 400 Bad Request). The HTTP response body **MAY** comprise a JSON-RPC *error
  12458. response* that has no `id`.
  12459. 5. If the input is a JSON-RPC *request*, the server **MUST** either
  12460. return `Content-Type: text/event-stream`, to initiate an SSE stream, or
  12461. `Content-Type: application/json`, to return one JSON object. The client **MUST**
  12462. support both these cases.
  12463. 6. If the server initiates an SSE stream:
  12464. * The SSE stream **SHOULD** eventually include JSON-RPC *response* for the
  12465. JSON-RPC *request* sent in the POST body.
  12466. * The server **MAY** send JSON-RPC *requests* and *notifications* before sending the
  12467. JSON-RPC *response*. These messages **SHOULD** relate to the originating client
  12468. *request*.
  12469. * The server **SHOULD NOT** close the SSE stream before sending the JSON-RPC *response*
  12470. for the received JSON-RPC *request*, unless the [session](#session-management)
  12471. expires.
  12472. * After the JSON-RPC *response* has been sent, the server **SHOULD** close the SSE
  12473. stream.
  12474. * Disconnection **MAY** occur at any time (e.g., due to network conditions).
  12475. Therefore:
  12476. * Disconnection **SHOULD NOT** be interpreted as the client cancelling its request.
  12477. * To cancel, the client **SHOULD** explicitly send an MCP `CancelledNotification`.
  12478. * To avoid message loss due to disconnection, the server **MAY** make the stream
  12479. [resumable](#resumability-and-redelivery).
  12480. ### Listening for Messages from the Server
  12481. 1. The client **MAY** issue an HTTP GET to the MCP endpoint. This can be used to open an
  12482. SSE stream, allowing the server to communicate to the client, without the client first
  12483. sending data via HTTP POST.
  12484. 2. The client **MUST** include an `Accept` header, listing `text/event-stream` as a
  12485. supported content type.
  12486. 3. The server **MUST** either return `Content-Type: text/event-stream` in response to
  12487. this HTTP GET, or else return HTTP 405 Method Not Allowed, indicating that the server
  12488. does not offer an SSE stream at this endpoint.
  12489. 4. If the server initiates an SSE stream:
  12490. * The server **MAY** send JSON-RPC *requests* and *notifications* on the stream.
  12491. * These messages **SHOULD** be unrelated to any concurrently-running JSON-RPC
  12492. *request* from the client.
  12493. * The server **MUST NOT** send a JSON-RPC *response* on the stream **unless**
  12494. [resuming](#resumability-and-redelivery) a stream associated with a previous client
  12495. request.
  12496. * The server **MAY** close the SSE stream at any time.
  12497. * The client **MAY** close the SSE stream at any time.
  12498. ### Multiple Connections
  12499. 1. The client **MAY** remain connected to multiple SSE streams simultaneously.
  12500. 2. The server **MUST** send each of its JSON-RPC messages on only one of the connected
  12501. streams; that is, it **MUST NOT** broadcast the same message across multiple streams.
  12502. * The risk of message loss **MAY** be mitigated by making the stream
  12503. [resumable](#resumability-and-redelivery).
  12504. ### Resumability and Redelivery
  12505. To support resuming broken connections, and redelivering messages that might otherwise be
  12506. lost:
  12507. 1. Servers **MAY** attach an `id` field to their SSE events, as described in the
  12508. [SSE standard](https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation).
  12509. * If present, the ID **MUST** be globally unique across all streams within that
  12510. [session](#session-management)—or all streams with that specific client, if session
  12511. management is not in use.
  12512. 2. If the client wishes to resume after a broken connection, it **SHOULD** issue an HTTP
  12513. GET to the MCP endpoint, and include the
  12514. [`Last-Event-ID`](https://html.spec.whatwg.org/multipage/server-sent-events.html#the-last-event-id-header)
  12515. header to indicate the last event ID it received.
  12516. * The server **MAY** use this header to replay messages that would have been sent
  12517. after the last event ID, *on the stream that was disconnected*, and to resume the
  12518. stream from that point.
  12519. * The server **MUST NOT** replay messages that would have been delivered on a
  12520. different stream.
  12521. In other words, these event IDs should be assigned by servers on a *per-stream* basis, to
  12522. act as a cursor within that particular stream.
  12523. ### Session Management
  12524. An MCP "session" consists of logically related interactions between a client and a
  12525. server, beginning with the [initialization phase](/specification/draft/basic/lifecycle). To support
  12526. servers which want to establish stateful sessions:
  12527. 1. A server using the Streamable HTTP transport **MAY** assign a session ID at
  12528. initialization time, by including it in an `Mcp-Session-Id` header on the HTTP
  12529. response containing the `InitializeResult`.
  12530. * The session ID **SHOULD** be globally unique and cryptographically secure (e.g., a
  12531. securely generated UUID, a JWT, or a cryptographic hash).
  12532. * The session ID **MUST** only contain visible ASCII characters (ranging from 0x21 to
  12533. 0x7E).
  12534. 2. If an `Mcp-Session-Id` is returned by the server during initialization, clients using
  12535. the Streamable HTTP transport **MUST** include it in the `Mcp-Session-Id` header on
  12536. all of their subsequent HTTP requests.
  12537. * Servers that require a session ID **SHOULD** respond to requests without an
  12538. `Mcp-Session-Id` header (other than initialization) with HTTP 400 Bad Request.
  12539. 3. The server **MAY** terminate the session at any time, after which it **MUST** respond
  12540. to requests containing that session ID with HTTP 404 Not Found.
  12541. 4. When a client receives HTTP 404 in response to a request containing an
  12542. `Mcp-Session-Id`, it **MUST** start a new session by sending a new `InitializeRequest`
  12543. without a session ID attached.
  12544. 5. Clients that no longer need a particular session (e.g., because the user is leaving
  12545. the client application) **SHOULD** send an HTTP DELETE to the MCP endpoint with the
  12546. `Mcp-Session-Id` header, to explicitly terminate the session.
  12547. * The server **MAY** respond to this request with HTTP 405 Method Not Allowed,
  12548. indicating that the server does not allow clients to terminate sessions.
  12549. ### Sequence Diagram
  12550. ```mermaid
  12551. sequenceDiagram
  12552. participant Client
  12553. participant Server
  12554. note over Client, Server: initialization
  12555. Client->>+Server: POST InitializeRequest
  12556. Server->>-Client: InitializeResponse<br>Mcp-Session-Id: 1868a90c...
  12557. Client->>+Server: POST InitializedNotification<br>Mcp-Session-Id: 1868a90c...
  12558. Server->>-Client: 202 Accepted
  12559. note over Client, Server: client requests
  12560. Client->>+Server: POST ... request ...<br>Mcp-Session-Id: 1868a90c...
  12561. alt single HTTP response
  12562. Server->>Client: ... response ...
  12563. else server opens SSE stream
  12564. loop while connection remains open
  12565. Server-)Client: ... SSE messages from server ...
  12566. end
  12567. Server-)Client: SSE event: ... response ...
  12568. end
  12569. deactivate Server
  12570. note over Client, Server: client notifications/responses
  12571. Client->>+Server: POST ... notification/response ...<br>Mcp-Session-Id: 1868a90c...
  12572. Server->>-Client: 202 Accepted
  12573. note over Client, Server: server requests
  12574. Client->>+Server: GET<br>Mcp-Session-Id: 1868a90c...
  12575. loop while connection remains open
  12576. Server-)Client: ... SSE messages from server ...
  12577. end
  12578. deactivate Server
  12579. ```
  12580. ### Protocol Version Header
  12581. If using HTTP, the client **MUST** include the `MCP-Protocol-Version: <protocol-version>` HTTP header on all subsequent requests to the MCP
  12582. server, allowing the MCP server to respond based on the MCP protocol version.
  12583. For example: `MCP-Protocol-Version: 2025-03-26`
  12584. The protocol version sent by the client **SHOULD** be the one [negotiated during
  12585. initialization](/specification/draft/basic/lifecycle#version-negotiation).
  12586. For backwards compatibility, if the server does *not* receive an `MCP-Protocol-Version`
  12587. header, and has no other way to identify the version - for example, by relying on the
  12588. protocol version negotiated during initialization - the server **SHOULD** assume protocol
  12589. version `2025-03-26`.
  12590. If the server receives a request with an invalid or unsupported
  12591. `MCP-Protocol-Version`, it **MUST** respond with `400 Bad Request`.
  12592. ### Backwards Compatibility
  12593. Clients and servers can maintain backwards compatibility with the deprecated [HTTP+SSE
  12594. transport](/specification/2024-11-05/basic/transports#http-with-sse) (from
  12595. protocol version 2024-11-05) as follows:
  12596. **Servers** wanting to support older clients should:
  12597. * Continue to host both the SSE and POST endpoints of the old transport, alongside the
  12598. new "MCP endpoint" defined for the Streamable HTTP transport.
  12599. * It is also possible to combine the old POST endpoint and the new MCP endpoint, but
  12600. this may introduce unneeded complexity.
  12601. **Clients** wanting to support older servers should:
  12602. 1. Accept an MCP server URL from the user, which may point to either a server using the
  12603. old transport or the new transport.
  12604. 2. Attempt to POST an `InitializeRequest` to the server URL, with an `Accept` header as
  12605. defined above:
  12606. * If it succeeds, the client can assume this is a server supporting the new Streamable
  12607. HTTP transport.
  12608. * If it fails with an HTTP 4xx status code (e.g., 405 Method Not Allowed or 404 Not
  12609. Found):
  12610. * Issue a GET request to the server URL, expecting that this will open an SSE stream
  12611. and return an `endpoint` event as the first event.
  12612. * When the `endpoint` event arrives, the client can assume this is a server running
  12613. the old HTTP+SSE transport, and should use that transport for all subsequent
  12614. communication.
  12615. ## Custom Transports
  12616. Clients and servers **MAY** implement additional custom transport mechanisms to suit
  12617. their specific needs. The protocol is transport-agnostic and can be implemented over any
  12618. communication channel that supports bidirectional message exchange.
  12619. Implementers who choose to support custom transports **MUST** ensure they preserve the
  12620. JSON-RPC message format and lifecycle requirements defined by MCP. Custom transports
  12621. **SHOULD** document their specific connection establishment and message exchange patterns
  12622. to aid interoperability.
  12623. # Cancellation
  12624. Source: https://modelcontextprotocol.io/specification/draft/basic/utilities/cancellation
  12625. <div id="enable-section-numbers" />
  12626. <Info>**Protocol Revision**: draft</Info>
  12627. The Model Context Protocol (MCP) supports optional cancellation of in-progress requests
  12628. through notification messages. Either side can send a cancellation notification to
  12629. indicate that a previously-issued request should be terminated.
  12630. ## Cancellation Flow
  12631. When a party wants to cancel an in-progress request, it sends a `notifications/cancelled`
  12632. notification containing:
  12633. * The ID of the request to cancel
  12634. * An optional reason string that can be logged or displayed
  12635. ```json
  12636. {
  12637. "jsonrpc": "2.0",
  12638. "method": "notifications/cancelled",
  12639. "params": {
  12640. "requestId": "123",
  12641. "reason": "User requested cancellation"
  12642. }
  12643. }
  12644. ```
  12645. ## Behavior Requirements
  12646. 1. Cancellation notifications **MUST** only reference requests that:
  12647. * Were previously issued in the same direction
  12648. * Are believed to still be in-progress
  12649. 2. The `initialize` request **MUST NOT** be cancelled by clients
  12650. 3. Receivers of cancellation notifications **SHOULD**:
  12651. * Stop processing the cancelled request
  12652. * Free associated resources
  12653. * Not send a response for the cancelled request
  12654. 4. Receivers **MAY** ignore cancellation notifications if:
  12655. * The referenced request is unknown
  12656. * Processing has already completed
  12657. * The request cannot be cancelled
  12658. 5. The sender of the cancellation notification **SHOULD** ignore any response to the
  12659. request that arrives afterward
  12660. ## Timing Considerations
  12661. Due to network latency, cancellation notifications may arrive after request processing
  12662. has completed, and potentially after a response has already been sent.
  12663. Both parties **MUST** handle these race conditions gracefully:
  12664. ```mermaid
  12665. sequenceDiagram
  12666. participant Client
  12667. participant Server
  12668. Client->>Server: Request (ID: 123)
  12669. Note over Server: Processing starts
  12670. Client--)Server: notifications/cancelled (ID: 123)
  12671. alt
  12672. Note over Server: Processing may have<br/>completed before<br/>cancellation arrives
  12673. else If not completed
  12674. Note over Server: Stop processing
  12675. end
  12676. ```
  12677. ## Implementation Notes
  12678. * Both parties **SHOULD** log cancellation reasons for debugging
  12679. * Application UIs **SHOULD** indicate when cancellation is requested
  12680. ## Error Handling
  12681. Invalid cancellation notifications **SHOULD** be ignored:
  12682. * Unknown request IDs
  12683. * Already completed requests
  12684. * Malformed notifications
  12685. This maintains the "fire and forget" nature of notifications while allowing for race
  12686. conditions in asynchronous communication.
  12687. # Ping
  12688. Source: https://modelcontextprotocol.io/specification/draft/basic/utilities/ping
  12689. <div id="enable-section-numbers" />
  12690. <Info>**Protocol Revision**: draft</Info>
  12691. The Model Context Protocol includes an optional ping mechanism that allows either party
  12692. to verify that their counterpart is still responsive and the connection is alive.
  12693. ## Overview
  12694. The ping functionality is implemented through a simple request/response pattern. Either
  12695. the client or server can initiate a ping by sending a `ping` request.
  12696. ## Message Format
  12697. A ping request is a standard JSON-RPC request with no parameters:
  12698. ```json
  12699. {
  12700. "jsonrpc": "2.0",
  12701. "id": "123",
  12702. "method": "ping"
  12703. }
  12704. ```
  12705. ## Behavior Requirements
  12706. 1. The receiver **MUST** respond promptly with an empty response:
  12707. ```json
  12708. {
  12709. "jsonrpc": "2.0",
  12710. "id": "123",
  12711. "result": {}
  12712. }
  12713. ```
  12714. 2. If no response is received within a reasonable timeout period, the sender **MAY**:
  12715. * Consider the connection stale
  12716. * Terminate the connection
  12717. * Attempt reconnection procedures
  12718. ## Usage Patterns
  12719. ```mermaid
  12720. sequenceDiagram
  12721. participant Sender
  12722. participant Receiver
  12723. Sender->>Receiver: ping request
  12724. Receiver->>Sender: empty response
  12725. ```
  12726. ## Implementation Considerations
  12727. * Implementations **SHOULD** periodically issue pings to detect connection health
  12728. * The frequency of pings **SHOULD** be configurable
  12729. * Timeouts **SHOULD** be appropriate for the network environment
  12730. * Excessive pinging **SHOULD** be avoided to reduce network overhead
  12731. ## Error Handling
  12732. * Timeouts **SHOULD** be treated as connection failures
  12733. * Multiple failed pings **MAY** trigger connection reset
  12734. * Implementations **SHOULD** log ping failures for diagnostics
  12735. # Progress
  12736. Source: https://modelcontextprotocol.io/specification/draft/basic/utilities/progress
  12737. <div id="enable-section-numbers" />
  12738. <Info>**Protocol Revision**: draft</Info>
  12739. The Model Context Protocol (MCP) supports optional progress tracking for long-running
  12740. operations through notification messages. Either side can send progress notifications to
  12741. provide updates about operation status.
  12742. ## Progress Flow
  12743. When a party wants to *receive* progress updates for a request, it includes a
  12744. `progressToken` in the request metadata.
  12745. * Progress tokens **MUST** be a string or integer value
  12746. * Progress tokens can be chosen by the sender using any means, but **MUST** be unique
  12747. across all active requests.
  12748. ```json
  12749. {
  12750. "jsonrpc": "2.0",
  12751. "id": 1,
  12752. "method": "some_method",
  12753. "params": {
  12754. "_meta": {
  12755. "progressToken": "abc123"
  12756. }
  12757. }
  12758. }
  12759. ```
  12760. The receiver **MAY** then send progress notifications containing:
  12761. * The original progress token
  12762. * The current progress value so far
  12763. * An optional "total" value
  12764. * An optional "message" value
  12765. ```json
  12766. {
  12767. "jsonrpc": "2.0",
  12768. "method": "notifications/progress",
  12769. "params": {
  12770. "progressToken": "abc123",
  12771. "progress": 50,
  12772. "total": 100,
  12773. "message": "Reticulating splines..."
  12774. }
  12775. }
  12776. ```
  12777. * The `progress` value **MUST** increase with each notification, even if the total is
  12778. unknown.
  12779. * The `progress` and the `total` values **MAY** be floating point.
  12780. * The `message` field **SHOULD** provide relevant human readable progress information.
  12781. ## Behavior Requirements
  12782. 1. Progress notifications **MUST** only reference tokens that:
  12783. * Were provided in an active request
  12784. * Are associated with an in-progress operation
  12785. 2. Receivers of progress requests **MAY**:
  12786. * Choose not to send any progress notifications
  12787. * Send notifications at whatever frequency they deem appropriate
  12788. * Omit the total value if unknown
  12789. ```mermaid
  12790. sequenceDiagram
  12791. participant Sender
  12792. participant Receiver
  12793. Note over Sender,Receiver: Request with progress token
  12794. Sender->>Receiver: Method request with progressToken
  12795. Note over Sender,Receiver: Progress updates
  12796. loop Progress Updates
  12797. Receiver-->>Sender: Progress notification (0.2/1.0)
  12798. Receiver-->>Sender: Progress notification (0.6/1.0)
  12799. Receiver-->>Sender: Progress notification (1.0/1.0)
  12800. end
  12801. Note over Sender,Receiver: Operation complete
  12802. Receiver->>Sender: Method response
  12803. ```
  12804. ## Implementation Notes
  12805. * Senders and receivers **SHOULD** track active progress tokens
  12806. * Both parties **SHOULD** implement rate limiting to prevent flooding
  12807. * Progress notifications **MUST** stop after completion
  12808. # Key Changes
  12809. Source: https://modelcontextprotocol.io/specification/draft/changelog
  12810. <div id="enable-section-numbers" />
  12811. This document lists changes made to the Model Context Protocol (MCP) specification since
  12812. the previous revision, [2025-03-26](/specification/2025-03-26).
  12813. ## Major changes
  12814. 1. Removed support for JSON-RPC **[batching](https://www.jsonrpc.org/specification#batch)**
  12815. (PR [#416](https://github.com/modelcontextprotocol/specification/pull/416))
  12816. 2. Added support for [structured tool output](/specification/draft/server/tools#structured-content)
  12817. (PR [#371](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/371))
  12818. 3. Classified MCP servers as [OAuth Resource Servers](/specification/draft/basic/authorization#authorization-server-discovery),
  12819. adding protected resource metadata to discover the corresponding Authorization server.
  12820. (PR [#338](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/338))
  12821. 4. Clarified [security considerations](/specification/draft/basic/authorization#security-considerations) and best practices
  12822. in the authorization spec and in a new [security best practices page](/specification/draft/basic/security_best_practices).
  12823. 5. Added support for **[elicitation](/specification/draft/client/elicitation)**, enabling servers to request additional
  12824. information from users during interactions.
  12825. (PR [#382](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/382))
  12826. 6. Added support for **[resource links](/specification/draft/server/tools#resource-links)** in
  12827. tool call results. (PR [#603](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/603))
  12828. ## Other schema changes
  12829. ## Full changelog
  12830. For a complete list of all changes that have been made since the last protocol revision,
  12831. [see GitHub](https://github.com/modelcontextprotocol/specification/compare/2025-03-26...draft).
  12832. # Elicitation
  12833. Source: https://modelcontextprotocol.io/specification/draft/client/elicitation
  12834. <div id="enable-section-numbers" />
  12835. <Info>**Protocol Revision**: draft</Info>
  12836. <Note>
  12837. Elicitation is newly introduced in this version of the MCP specification and its design may evolve in future protocol versions.
  12838. </Note>
  12839. The Model Context Protocol (MCP) provides a standardized way for servers to request additional
  12840. information from users through the client during interactions. This flow allows clients to
  12841. maintain control over user interactions and data sharing while enabling servers to gather
  12842. necessary information dynamically.
  12843. Servers request structured data from users with JSON schemas to validate responses.
  12844. ## User Interaction Model
  12845. Elicitation in MCP allows servers to implement interactive workflows by enabling user input
  12846. requests to occur *nested* inside other MCP server features.
  12847. Implementations are free to expose elicitation through any interface pattern that suits
  12848. their needs—the protocol itself does not mandate any specific user interaction
  12849. model.
  12850. <Warning>
  12851. For trust & safety and security:
  12852. * Servers **MUST NOT** use elicitation to request sensitive information.
  12853. Applications **SHOULD**:
  12854. * Provide UI that makes it clear which server is requesting information
  12855. * Allow users to review and modify their responses before sending
  12856. * Respect user privacy and provide clear decline and cancel options
  12857. </Warning>
  12858. ## Capabilities
  12859. Clients that support elicitation **MUST** declare the `elicitation` capability during
  12860. [initialization](/specification/draft/basic/lifecycle#initialization):
  12861. ```json
  12862. {
  12863. "capabilities": {
  12864. "elicitation": {}
  12865. }
  12866. }
  12867. ```
  12868. ## Protocol Messages
  12869. ### Creating Elicitation Requests
  12870. To request information from a user, servers send an `elicitation/create` request:
  12871. #### Simple Text Request
  12872. **Request:**
  12873. ```json
  12874. {
  12875. "jsonrpc": "2.0",
  12876. "id": 1,
  12877. "method": "elicitation/create",
  12878. "params": {
  12879. "message": "Please provide your GitHub username",
  12880. "requestedSchema": {
  12881. "type": "object",
  12882. "properties": {
  12883. "name": {
  12884. "type": "string"
  12885. }
  12886. },
  12887. "required": ["name"]
  12888. }
  12889. }
  12890. }
  12891. ```
  12892. **Response:**
  12893. ```json
  12894. {
  12895. "jsonrpc": "2.0",
  12896. "id": 1,
  12897. "result": {
  12898. "action": "accept",
  12899. "content": {
  12900. "name": "octocat"
  12901. }
  12902. }
  12903. }
  12904. ```
  12905. #### Structured Data Request
  12906. **Request:**
  12907. ```json
  12908. {
  12909. "jsonrpc": "2.0",
  12910. "id": 2,
  12911. "method": "elicitation/create",
  12912. "params": {
  12913. "message": "Please provide your contact information",
  12914. "requestedSchema": {
  12915. "type": "object",
  12916. "properties": {
  12917. "name": {
  12918. "type": "string",
  12919. "description": "Your full name"
  12920. },
  12921. "email": {
  12922. "type": "string",
  12923. "format": "email",
  12924. "description": "Your email address"
  12925. },
  12926. "age": {
  12927. "type": "number",
  12928. "minimum": 18,
  12929. "description": "Your age"
  12930. }
  12931. },
  12932. "required": ["name", "email"]
  12933. }
  12934. }
  12935. }
  12936. ```
  12937. **Response:**
  12938. ```json
  12939. {
  12940. "jsonrpc": "2.0",
  12941. "id": 2,
  12942. "result": {
  12943. "action": "accept",
  12944. "content": {
  12945. "name": "Monalisa Octocat",
  12946. "email": "octocat@github.com",
  12947. "age": 30
  12948. }
  12949. }
  12950. }
  12951. ```
  12952. **Decline Response Example:**
  12953. ```json
  12954. {
  12955. "jsonrpc": "2.0",
  12956. "id": 2,
  12957. "result": {
  12958. "action": "decline"
  12959. }
  12960. }
  12961. ```
  12962. **Cancel Response Example:**
  12963. ```json
  12964. {
  12965. "jsonrpc": "2.0",
  12966. "id": 2,
  12967. "result": {
  12968. "action": "cancel"
  12969. }
  12970. }
  12971. ```
  12972. ## Message Flow
  12973. ```mermaid
  12974. sequenceDiagram
  12975. participant Server
  12976. participant Client
  12977. participant User
  12978. Note over Server,Client: Server initiates elicitation
  12979. Server->>Client: elicitation/create
  12980. Note over Client,User: Human interaction
  12981. Client->>User: Present elicitation UI
  12982. User-->>Client: Provide requested information
  12983. Note over Server,Client: Complete request
  12984. Client-->>Server: Return user response
  12985. Note over Server: Continue processing with new information
  12986. ```
  12987. ## Request Schema
  12988. The `requestedSchema` field allows servers to define the structure of the expected response using a restricted subset of JSON Schema. To simplify implementation for clients, elicitation schemas are limited to flat objects with primitive properties only:
  12989. ```json
  12990. "requestedSchema": {
  12991. "type": "object",
  12992. "properties": {
  12993. "propertyName": {
  12994. "type": "string",
  12995. "title": "Display Name",
  12996. "description": "Description of the property"
  12997. },
  12998. "anotherProperty": {
  12999. "type": "number",
  13000. "minimum": 0,
  13001. "maximum": 100
  13002. }
  13003. },
  13004. "required": ["propertyName"]
  13005. }
  13006. ```
  13007. ### Supported Schema Types
  13008. The schema is restricted to these primitive types:
  13009. 1. **String Schema**
  13010. ```json
  13011. {
  13012. "type": "string",
  13013. "title": "Display Name",
  13014. "description": "Description text",
  13015. "minLength": 3,
  13016. "maxLength": 50,
  13017. "pattern": "^[A-Za-z]+$",
  13018. "format": "email"
  13019. }
  13020. ```
  13021. Supported formats: `email`, `uri`, `date`, `date-time`
  13022. 2. **Number Schema**
  13023. ```json
  13024. {
  13025. "type": "number", // or "integer"
  13026. "title": "Display Name",
  13027. "description": "Description text",
  13028. "minimum": 0,
  13029. "maximum": 100
  13030. }
  13031. ```
  13032. 3. **Boolean Schema**
  13033. ```json
  13034. {
  13035. "type": "boolean",
  13036. "title": "Display Name",
  13037. "description": "Description text",
  13038. "default": false
  13039. }
  13040. ```
  13041. 4. **Enum Schema**
  13042. ```json
  13043. {
  13044. "type": "string",
  13045. "title": "Display Name",
  13046. "description": "Description text",
  13047. "enum": ["option1", "option2", "option3"],
  13048. "enumNames": ["Option 1", "Option 2", "Option 3"]
  13049. }
  13050. ```
  13051. Clients can use this schema to:
  13052. 1. Generate appropriate input forms
  13053. 2. Validate user input before sending
  13054. 3. Provide better guidance to users
  13055. Note that complex nested structures, arrays of objects, and other advanced JSON Schema features are intentionally not supported to simplify client implementation.
  13056. ## Response Actions
  13057. Elicitation responses use a three-action model to clearly distinguish between different user actions:
  13058. ```json
  13059. {
  13060. "jsonrpc": "2.0",
  13061. "id": 1,
  13062. "result": {
  13063. "action": "accept", // or "decline" or "cancel"
  13064. "content": {
  13065. "propertyName": "value",
  13066. "anotherProperty": 42
  13067. }
  13068. }
  13069. }
  13070. ```
  13071. The three response actions are:
  13072. 1. **Accept** (`action: "accept"`): User explicitly approved and submitted with data
  13073. * The `content` field contains the submitted data matching the requested schema
  13074. * Example: User clicked "Submit", "OK", "Confirm", etc.
  13075. 2. **Decline** (`action: "decline"`): User explicitly rejected the request
  13076. * The `content` field is typically omitted
  13077. * Example: User clicked "Decline", "Reject", "No", etc.
  13078. 3. **Cancel** (`action: "cancel"`): User dismissed without making an explicit choice
  13079. * The `content` field is typically omitted
  13080. * Example: User closed the dialog, clicked outside, pressed Escape, etc.
  13081. Servers should handle each state appropriately:
  13082. * **Accept**: Process the submitted data
  13083. * **Decline**: Handle explicit rejection (e.g., offer alternatives)
  13084. * **Cancel**: Handle dismissal (e.g., prompt again later)
  13085. ## Security Considerations
  13086. 1. Servers **MUST NOT** request sensitive information through elicitation
  13087. 2. Clients **SHOULD** implement user approval controls
  13088. 3. Both parties **SHOULD** validate elicitation content against the provided schema
  13089. 4. Clients **SHOULD** provide clear indication of which server is requesting information
  13090. 5. Clients **SHOULD** allow users to reject elicitation requests at any time
  13091. 6. Clients **SHOULD** implement rate limiting
  13092. 7. Clients **SHOULD** present elicitation requests in a way that makes it clear what information is being requested and why
  13093. # Roots
  13094. Source: https://modelcontextprotocol.io/specification/draft/client/roots
  13095. <div id="enable-section-numbers" />
  13096. <Info>**Protocol Revision**: draft</Info>
  13097. The Model Context Protocol (MCP) provides a standardized way for clients to expose
  13098. filesystem "roots" to servers. Roots define the boundaries of where servers can operate
  13099. within the filesystem, allowing them to understand which directories and files they have
  13100. access to. Servers can request the list of roots from supporting clients and receive
  13101. notifications when that list changes.
  13102. ## User Interaction Model
  13103. Roots in MCP are typically exposed through workspace or project configuration interfaces.
  13104. For example, implementations could offer a workspace/project picker that allows users to
  13105. select directories and files the server should have access to. This can be combined with
  13106. automatic workspace detection from version control systems or project files.
  13107. However, implementations are free to expose roots through any interface pattern that
  13108. suits their needs—the protocol itself does not mandate any specific user
  13109. interaction model.
  13110. ## Capabilities
  13111. Clients that support roots **MUST** declare the `roots` capability during
  13112. [initialization](/specification/draft/basic/lifecycle#initialization):
  13113. ```json
  13114. {
  13115. "capabilities": {
  13116. "roots": {
  13117. "listChanged": true
  13118. }
  13119. }
  13120. }
  13121. ```
  13122. `listChanged` indicates whether the client will emit notifications when the list of roots
  13123. changes.
  13124. ## Protocol Messages
  13125. ### Listing Roots
  13126. To retrieve roots, servers send a `roots/list` request:
  13127. **Request:**
  13128. ```json
  13129. {
  13130. "jsonrpc": "2.0",
  13131. "id": 1,
  13132. "method": "roots/list"
  13133. }
  13134. ```
  13135. **Response:**
  13136. ```json
  13137. {
  13138. "jsonrpc": "2.0",
  13139. "id": 1,
  13140. "result": {
  13141. "roots": [
  13142. {
  13143. "uri": "file:///home/user/projects/myproject",
  13144. "name": "My Project"
  13145. }
  13146. ]
  13147. }
  13148. }
  13149. ```
  13150. ### Root List Changes
  13151. When roots change, clients that support `listChanged` **MUST** send a notification:
  13152. ```json
  13153. {
  13154. "jsonrpc": "2.0",
  13155. "method": "notifications/roots/list_changed"
  13156. }
  13157. ```
  13158. ## Message Flow
  13159. ```mermaid
  13160. sequenceDiagram
  13161. participant Server
  13162. participant Client
  13163. Note over Server,Client: Discovery
  13164. Server->>Client: roots/list
  13165. Client-->>Server: Available roots
  13166. Note over Server,Client: Changes
  13167. Client--)Server: notifications/roots/list_changed
  13168. Server->>Client: roots/list
  13169. Client-->>Server: Updated roots
  13170. ```
  13171. ## Data Types
  13172. ### Root
  13173. A root definition includes:
  13174. * `uri`: Unique identifier for the root. This **MUST** be a `file://` URI in the current
  13175. specification.
  13176. * `name`: Optional human-readable name for display purposes.
  13177. Example roots for different use cases:
  13178. #### Project Directory
  13179. ```json
  13180. {
  13181. "uri": "file:///home/user/projects/myproject",
  13182. "name": "My Project"
  13183. }
  13184. ```
  13185. #### Multiple Repositories
  13186. ```json
  13187. [
  13188. {
  13189. "uri": "file:///home/user/repos/frontend",
  13190. "name": "Frontend Repository"
  13191. },
  13192. {
  13193. "uri": "file:///home/user/repos/backend",
  13194. "name": "Backend Repository"
  13195. }
  13196. ]
  13197. ```
  13198. ## Error Handling
  13199. Clients **SHOULD** return standard JSON-RPC errors for common failure cases:
  13200. * Client does not support roots: `-32601` (Method not found)
  13201. * Internal errors: `-32603`
  13202. Example error:
  13203. ```json
  13204. {
  13205. "jsonrpc": "2.0",
  13206. "id": 1,
  13207. "error": {
  13208. "code": -32601,
  13209. "message": "Roots not supported",
  13210. "data": {
  13211. "reason": "Client does not have roots capability"
  13212. }
  13213. }
  13214. }
  13215. ```
  13216. ## Security Considerations
  13217. 1. Clients **MUST**:
  13218. * Only expose roots with appropriate permissions
  13219. * Validate all root URIs to prevent path traversal
  13220. * Implement proper access controls
  13221. * Monitor root accessibility
  13222. 2. Servers **SHOULD**:
  13223. * Handle cases where roots become unavailable
  13224. * Respect root boundaries during operations
  13225. * Validate all paths against provided roots
  13226. ## Implementation Guidelines
  13227. 1. Clients **SHOULD**:
  13228. * Prompt users for consent before exposing roots to servers
  13229. * Provide clear user interfaces for root management
  13230. * Validate root accessibility before exposing
  13231. * Monitor for root changes
  13232. 2. Servers **SHOULD**:
  13233. * Check for roots capability before usage
  13234. * Handle root list changes gracefully
  13235. * Respect root boundaries in operations
  13236. * Cache root information appropriately
  13237. # Sampling
  13238. Source: https://modelcontextprotocol.io/specification/draft/client/sampling
  13239. <div id="enable-section-numbers" />
  13240. <Info>**Protocol Revision**: draft</Info>
  13241. The Model Context Protocol (MCP) provides a standardized way for servers to request LLM
  13242. sampling ("completions" or "generations") from language models via clients. This flow
  13243. allows clients to maintain control over model access, selection, and permissions while
  13244. enabling servers to leverage AI capabilities—with no server API keys necessary.
  13245. Servers can request text, audio, or image-based interactions and optionally include
  13246. context from MCP servers in their prompts.
  13247. ## User Interaction Model
  13248. Sampling in MCP allows servers to implement agentic behaviors, by enabling LLM calls to
  13249. occur *nested* inside other MCP server features.
  13250. Implementations are free to expose sampling through any interface pattern that suits
  13251. their needs—the protocol itself does not mandate any specific user interaction
  13252. model.
  13253. <Warning>
  13254. For trust & safety and security, there **SHOULD** always
  13255. be a human in the loop with the ability to deny sampling requests.
  13256. Applications **SHOULD**:
  13257. * Provide UI that makes it easy and intuitive to review sampling requests
  13258. * Allow users to view and edit prompts before sending
  13259. * Present generated responses for review before delivery
  13260. </Warning>
  13261. ## Capabilities
  13262. Clients that support sampling **MUST** declare the `sampling` capability during
  13263. [initialization](/specification/draft/basic/lifecycle#initialization):
  13264. ```json
  13265. {
  13266. "capabilities": {
  13267. "sampling": {}
  13268. }
  13269. }
  13270. ```
  13271. ## Protocol Messages
  13272. ### Creating Messages
  13273. To request a language model generation, servers send a `sampling/createMessage` request:
  13274. **Request:**
  13275. ```json
  13276. {
  13277. "jsonrpc": "2.0",
  13278. "id": 1,
  13279. "method": "sampling/createMessage",
  13280. "params": {
  13281. "messages": [
  13282. {
  13283. "role": "user",
  13284. "content": {
  13285. "type": "text",
  13286. "text": "What is the capital of France?"
  13287. }
  13288. }
  13289. ],
  13290. "modelPreferences": {
  13291. "hints": [
  13292. {
  13293. "name": "claude-3-sonnet"
  13294. }
  13295. ],
  13296. "intelligencePriority": 0.8,
  13297. "speedPriority": 0.5
  13298. },
  13299. "systemPrompt": "You are a helpful assistant.",
  13300. "maxTokens": 100
  13301. }
  13302. }
  13303. ```
  13304. **Response:**
  13305. ```json
  13306. {
  13307. "jsonrpc": "2.0",
  13308. "id": 1,
  13309. "result": {
  13310. "role": "assistant",
  13311. "content": {
  13312. "type": "text",
  13313. "text": "The capital of France is Paris."
  13314. },
  13315. "model": "claude-3-sonnet-20240307",
  13316. "stopReason": "endTurn"
  13317. }
  13318. }
  13319. ```
  13320. ## Message Flow
  13321. ```mermaid
  13322. sequenceDiagram
  13323. participant Server
  13324. participant Client
  13325. participant User
  13326. participant LLM
  13327. Note over Server,Client: Server initiates sampling
  13328. Server->>Client: sampling/createMessage
  13329. Note over Client,User: Human-in-the-loop review
  13330. Client->>User: Present request for approval
  13331. User-->>Client: Review and approve/modify
  13332. Note over Client,LLM: Model interaction
  13333. Client->>LLM: Forward approved request
  13334. LLM-->>Client: Return generation
  13335. Note over Client,User: Response review
  13336. Client->>User: Present response for approval
  13337. User-->>Client: Review and approve/modify
  13338. Note over Server,Client: Complete request
  13339. Client-->>Server: Return approved response
  13340. ```
  13341. ## Data Types
  13342. ### Messages
  13343. Sampling messages can contain:
  13344. #### Text Content
  13345. ```json
  13346. {
  13347. "type": "text",
  13348. "text": "The message content"
  13349. }
  13350. ```
  13351. #### Image Content
  13352. ```json
  13353. {
  13354. "type": "image",
  13355. "data": "base64-encoded-image-data",
  13356. "mimeType": "image/jpeg"
  13357. }
  13358. ```
  13359. #### Audio Content
  13360. ```json
  13361. {
  13362. "type": "audio",
  13363. "data": "base64-encoded-audio-data",
  13364. "mimeType": "audio/wav"
  13365. }
  13366. ```
  13367. ### Model Preferences
  13368. Model selection in MCP requires careful abstraction since servers and clients may use
  13369. different AI providers with distinct model offerings. A server cannot simply request a
  13370. specific model by name since the client may not have access to that exact model or may
  13371. prefer to use a different provider's equivalent model.
  13372. To solve this, MCP implements a preference system that combines abstract capability
  13373. priorities with optional model hints:
  13374. #### Capability Priorities
  13375. Servers express their needs through three normalized priority values (0-1):
  13376. * `costPriority`: How important is minimizing costs? Higher values prefer cheaper models.
  13377. * `speedPriority`: How important is low latency? Higher values prefer faster models.
  13378. * `intelligencePriority`: How important are advanced capabilities? Higher values prefer
  13379. more capable models.
  13380. #### Model Hints
  13381. While priorities help select models based on characteristics, `hints` allow servers to
  13382. suggest specific models or model families:
  13383. * Hints are treated as substrings that can match model names flexibly
  13384. * Multiple hints are evaluated in order of preference
  13385. * Clients **MAY** map hints to equivalent models from different providers
  13386. * Hints are advisory—clients make final model selection
  13387. For example:
  13388. ```json
  13389. {
  13390. "hints": [
  13391. { "name": "claude-3-sonnet" }, // Prefer Sonnet-class models
  13392. { "name": "claude" } // Fall back to any Claude model
  13393. ],
  13394. "costPriority": 0.3, // Cost is less important
  13395. "speedPriority": 0.8, // Speed is very important
  13396. "intelligencePriority": 0.5 // Moderate capability needs
  13397. }
  13398. ```
  13399. The client processes these preferences to select an appropriate model from its available
  13400. options. For instance, if the client doesn't have access to Claude models but has Gemini,
  13401. it might map the sonnet hint to `gemini-1.5-pro` based on similar capabilities.
  13402. ## Error Handling
  13403. Clients **SHOULD** return errors for common failure cases:
  13404. Example error:
  13405. ```json
  13406. {
  13407. "jsonrpc": "2.0",
  13408. "id": 1,
  13409. "error": {
  13410. "code": -1,
  13411. "message": "User rejected sampling request"
  13412. }
  13413. }
  13414. ```
  13415. ## Security Considerations
  13416. 1. Clients **SHOULD** implement user approval controls
  13417. 2. Both parties **SHOULD** validate message content
  13418. 3. Clients **SHOULD** respect model preference hints
  13419. 4. Clients **SHOULD** implement rate limiting
  13420. 5. Both parties **MUST** handle sensitive data appropriately
  13421. # Specification
  13422. Source: https://modelcontextprotocol.io/specification/draft/index
  13423. <div id="enable-section-numbers" />
  13424. [Model Context Protocol](https://modelcontextprotocol.io) (MCP) is an open protocol that
  13425. enables seamless integration between LLM applications and external data sources and
  13426. tools. Whether you're building an AI-powered IDE, enhancing a chat interface, or creating
  13427. custom AI workflows, MCP provides a standardized way to connect LLMs with the context
  13428. they need.
  13429. This specification defines the authoritative protocol requirements, based on the
  13430. TypeScript schema in
  13431. [schema.ts](https://github.com/modelcontextprotocol/specification/blob/main/schema/draft/schema.ts).
  13432. For implementation guides and examples, visit
  13433. [modelcontextprotocol.io](https://modelcontextprotocol.io).
  13434. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD
  13435. NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be
  13436. interpreted as described in [BCP 14](https://datatracker.ietf.org/doc/html/bcp14)
  13437. \[[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)]
  13438. \[[RFC8174](https://datatracker.ietf.org/doc/html/rfc8174)] when, and only when, they
  13439. appear in all capitals, as shown here.
  13440. ## Overview
  13441. MCP provides a standardized way for applications to:
  13442. * Share contextual information with language models
  13443. * Expose tools and capabilities to AI systems
  13444. * Build composable integrations and workflows
  13445. The protocol uses [JSON-RPC](https://www.jsonrpc.org/) 2.0 messages to establish
  13446. communication between:
  13447. * **Hosts**: LLM applications that initiate connections
  13448. * **Clients**: Connectors within the host application
  13449. * **Servers**: Services that provide context and capabilities
  13450. MCP takes some inspiration from the
  13451. [Language Server Protocol](https://microsoft.github.io/language-server-protocol/), which
  13452. standardizes how to add support for programming languages across a whole ecosystem of
  13453. development tools. In a similar way, MCP standardizes how to integrate additional context
  13454. and tools into the ecosystem of AI applications.
  13455. ## Key Details
  13456. ### Base Protocol
  13457. * [JSON-RPC](https://www.jsonrpc.org/) message format
  13458. * Stateful connections
  13459. * Server and client capability negotiation
  13460. ### Features
  13461. Servers offer any of the following features to clients:
  13462. * **Resources**: Context and data, for the user or the AI model to use
  13463. * **Prompts**: Templated messages and workflows for users
  13464. * **Tools**: Functions for the AI model to execute
  13465. Clients may offer the following features to servers:
  13466. * **Sampling**: Server-initiated agentic behaviors and recursive LLM interactions
  13467. * **Elicitation**: Server-initiated requests for additional information from users
  13468. ### Additional Utilities
  13469. * Configuration
  13470. * Progress tracking
  13471. * Cancellation
  13472. * Error reporting
  13473. * Logging
  13474. ## Security and Trust & Safety
  13475. The Model Context Protocol enables powerful capabilities through arbitrary data access
  13476. and code execution paths. With this power comes important security and trust
  13477. considerations that all implementors must carefully address.
  13478. ### Key Principles
  13479. 1. **User Consent and Control**
  13480. * Users must explicitly consent to and understand all data access and operations
  13481. * Users must retain control over what data is shared and what actions are taken
  13482. * Implementors should provide clear UIs for reviewing and authorizing activities
  13483. 2. **Data Privacy**
  13484. * Hosts must obtain explicit user consent before exposing user data to servers
  13485. * Hosts must not transmit resource data elsewhere without user consent
  13486. * User data should be protected with appropriate access controls
  13487. 3. **Tool Safety**
  13488. * Tools represent arbitrary code execution and must be treated with appropriate
  13489. caution.
  13490. * In particular, descriptions of tool behavior such as annotations should be
  13491. considered untrusted, unless obtained from a trusted server.
  13492. * Hosts must obtain explicit user consent before invoking any tool
  13493. * Users should understand what each tool does before authorizing its use
  13494. 4. **LLM Sampling Controls**
  13495. * Users must explicitly approve any LLM sampling requests
  13496. * Users should control:
  13497. * Whether sampling occurs at all
  13498. * The actual prompt that will be sent
  13499. * What results the server can see
  13500. * The protocol intentionally limits server visibility into prompts
  13501. ### Implementation Guidelines
  13502. While MCP itself cannot enforce these security principles at the protocol level,
  13503. implementors **SHOULD**:
  13504. 1. Build robust consent and authorization flows into their applications
  13505. 2. Provide clear documentation of security implications
  13506. 3. Implement appropriate access controls and data protections
  13507. 4. Follow security best practices in their integrations
  13508. 5. Consider privacy implications in their feature designs
  13509. ## Learn More
  13510. Explore the detailed specification for each protocol component:
  13511. <CardGroup cols={5}>
  13512. <Card title="Architecture" icon="sitemap" href="/specification/draft/architecture" />
  13513. <Card title="Base Protocol" icon="code" href="/specification/draft/basic" />
  13514. <Card title="Server Features" icon="server" href="/specification/draft/server" />
  13515. <Card title="Client Features" icon="user" href="/specification/draft/client" />
  13516. <Card title="Contributing" icon="pencil" href="/specification/contributing" />
  13517. </CardGroup>
  13518. # Overview
  13519. Source: https://modelcontextprotocol.io/specification/draft/server/index
  13520. <Info>**Protocol Revision**: draft</Info>
  13521. Servers provide the fundamental building blocks for adding context to language models via
  13522. MCP. These primitives enable rich interactions between clients, servers, and language
  13523. models:
  13524. * **Prompts**: Pre-defined templates or instructions that guide language model
  13525. interactions
  13526. * **Resources**: Structured data or content that provides additional context to the model
  13527. * **Tools**: Executable functions that allow models to perform actions or retrieve
  13528. information
  13529. Each primitive can be summarized in the following control hierarchy:
  13530. | Primitive | Control | Description | Example |
  13531. | --------- | ---------------------- | -------------------------------------------------- | ------------------------------- |
  13532. | Prompts | User-controlled | Interactive templates invoked by user choice | Slash commands, menu options |
  13533. | Resources | Application-controlled | Contextual data attached and managed by the client | File contents, git history |
  13534. | Tools | Model-controlled | Functions exposed to the LLM to take actions | API POST requests, file writing |
  13535. Explore these key primitives in more detail below:
  13536. <CardGroup cols={3}>
  13537. <Card title="Prompts" icon="message" href="/specification/draft/server/prompts" />
  13538. <Card title="Resources" icon="file-lines" href="/specification/draft/server/resources" />
  13539. <Card title="Tools" icon="wrench" href="/specification/draft/server/tools" />
  13540. </CardGroup>
  13541. # Prompts
  13542. Source: https://modelcontextprotocol.io/specification/draft/server/prompts
  13543. <div id="enable-section-numbers" />
  13544. <Info>**Protocol Revision**: draft</Info>
  13545. The Model Context Protocol (MCP) provides a standardized way for servers to expose prompt
  13546. templates to clients. Prompts allow servers to provide structured messages and
  13547. instructions for interacting with language models. Clients can discover available
  13548. prompts, retrieve their contents, and provide arguments to customize them.
  13549. ## User Interaction Model
  13550. Prompts are designed to be **user-controlled**, meaning they are exposed from servers to
  13551. clients with the intention of the user being able to explicitly select them for use.
  13552. Typically, prompts would be triggered through user-initiated commands in the user
  13553. interface, which allows users to naturally discover and invoke available prompts.
  13554. For example, as slash commands:
  13555. ![Example of prompt exposed as slash command](https://mintlify.s3.us-west-1.amazonaws.com/mcp/specification/draft/server/slash-command.png)
  13556. However, implementors are free to expose prompts through any interface pattern that suits
  13557. their needs—the protocol itself does not mandate any specific user interaction
  13558. model.
  13559. ## Capabilities
  13560. Servers that support prompts **MUST** declare the `prompts` capability during
  13561. [initialization](/specification/draft/basic/lifecycle#initialization):
  13562. ```json
  13563. {
  13564. "capabilities": {
  13565. "prompts": {
  13566. "listChanged": true
  13567. }
  13568. }
  13569. }
  13570. ```
  13571. `listChanged` indicates whether the server will emit notifications when the list of
  13572. available prompts changes.
  13573. ## Protocol Messages
  13574. ### Listing Prompts
  13575. To retrieve available prompts, clients send a `prompts/list` request. This operation
  13576. supports [pagination](/specification/draft/server/utilities/pagination).
  13577. **Request:**
  13578. ```json
  13579. {
  13580. "jsonrpc": "2.0",
  13581. "id": 1,
  13582. "method": "prompts/list",
  13583. "params": {
  13584. "cursor": "optional-cursor-value"
  13585. }
  13586. }
  13587. ```
  13588. **Response:**
  13589. ```json
  13590. {
  13591. "jsonrpc": "2.0",
  13592. "id": 1,
  13593. "result": {
  13594. "prompts": [
  13595. {
  13596. "name": "code_review",
  13597. "description": "Asks the LLM to analyze code quality and suggest improvements",
  13598. "arguments": [
  13599. {
  13600. "name": "code",
  13601. "description": "The code to review",
  13602. "required": true
  13603. }
  13604. ]
  13605. }
  13606. ],
  13607. "nextCursor": "next-page-cursor"
  13608. }
  13609. }
  13610. ```
  13611. ### Getting a Prompt
  13612. To retrieve a specific prompt, clients send a `prompts/get` request. Arguments may be
  13613. auto-completed through [the completion API](/specification/draft/server/utilities/completion).
  13614. **Request:**
  13615. ```json
  13616. {
  13617. "jsonrpc": "2.0",
  13618. "id": 2,
  13619. "method": "prompts/get",
  13620. "params": {
  13621. "name": "code_review",
  13622. "arguments": {
  13623. "code": "def hello():\n print('world')"
  13624. }
  13625. }
  13626. }
  13627. ```
  13628. **Response:**
  13629. ```json
  13630. {
  13631. "jsonrpc": "2.0",
  13632. "id": 2,
  13633. "result": {
  13634. "description": "Code review prompt",
  13635. "messages": [
  13636. {
  13637. "role": "user",
  13638. "content": {
  13639. "type": "text",
  13640. "text": "Please review this Python code:\ndef hello():\n print('world')"
  13641. }
  13642. }
  13643. ]
  13644. }
  13645. }
  13646. ```
  13647. ### List Changed Notification
  13648. When the list of available prompts changes, servers that declared the `listChanged`
  13649. capability **SHOULD** send a notification:
  13650. ```json
  13651. {
  13652. "jsonrpc": "2.0",
  13653. "method": "notifications/prompts/list_changed"
  13654. }
  13655. ```
  13656. ## Message Flow
  13657. ```mermaid
  13658. sequenceDiagram
  13659. participant Client
  13660. participant Server
  13661. Note over Client,Server: Discovery
  13662. Client->>Server: prompts/list
  13663. Server-->>Client: List of prompts
  13664. Note over Client,Server: Usage
  13665. Client->>Server: prompts/get
  13666. Server-->>Client: Prompt content
  13667. opt listChanged
  13668. Note over Client,Server: Changes
  13669. Server--)Client: prompts/list_changed
  13670. Client->>Server: prompts/list
  13671. Server-->>Client: Updated prompts
  13672. end
  13673. ```
  13674. ## Data Types
  13675. ### Prompt
  13676. A prompt definition includes:
  13677. * `name`: Unique identifier for the prompt
  13678. * `description`: Optional human-readable description
  13679. * `arguments`: Optional list of arguments for customization
  13680. ### PromptMessage
  13681. Messages in a prompt can contain:
  13682. * `role`: Either "user" or "assistant" to indicate the speaker
  13683. * `content`: One of the following content types:
  13684. #### Text Content
  13685. Text content represents plain text messages:
  13686. ```json
  13687. {
  13688. "type": "text",
  13689. "text": "The text content of the message"
  13690. }
  13691. ```
  13692. This is the most common content type used for natural language interactions.
  13693. #### Image Content
  13694. Image content allows including visual information in messages:
  13695. ```json
  13696. {
  13697. "type": "image",
  13698. "data": "base64-encoded-image-data",
  13699. "mimeType": "image/png"
  13700. }
  13701. ```
  13702. The image data **MUST** be base64-encoded and include a valid MIME type. This enables
  13703. multi-modal interactions where visual context is important.
  13704. #### Audio Content
  13705. Audio content allows including audio information in messages:
  13706. ```json
  13707. {
  13708. "type": "audio",
  13709. "data": "base64-encoded-audio-data",
  13710. "mimeType": "audio/wav"
  13711. }
  13712. ```
  13713. The audio data MUST be base64-encoded and include a valid MIME type. This enables
  13714. multi-modal interactions where audio context is important.
  13715. #### Embedded Resources
  13716. Embedded resources allow referencing server-side resources directly in messages:
  13717. ```json
  13718. {
  13719. "type": "resource",
  13720. "resource": {
  13721. "uri": "resource://example",
  13722. "mimeType": "text/plain",
  13723. "text": "Resource content"
  13724. }
  13725. }
  13726. ```
  13727. Resources can contain either text or binary (blob) data and **MUST** include:
  13728. * A valid resource URI
  13729. * The appropriate MIME type
  13730. * Either text content or base64-encoded blob data
  13731. Embedded resources enable prompts to seamlessly incorporate server-managed content like
  13732. documentation, code samples, or other reference materials directly into the conversation
  13733. flow.
  13734. ## Error Handling
  13735. Servers **SHOULD** return standard JSON-RPC errors for common failure cases:
  13736. * Invalid prompt name: `-32602` (Invalid params)
  13737. * Missing required arguments: `-32602` (Invalid params)
  13738. * Internal errors: `-32603` (Internal error)
  13739. ## Implementation Considerations
  13740. 1. Servers **SHOULD** validate prompt arguments before processing
  13741. 2. Clients **SHOULD** handle pagination for large prompt lists
  13742. 3. Both parties **SHOULD** respect capability negotiation
  13743. ## Security
  13744. Implementations **MUST** carefully validate all prompt inputs and outputs to prevent
  13745. injection attacks or unauthorized access to resources.
  13746. # Resources
  13747. Source: https://modelcontextprotocol.io/specification/draft/server/resources
  13748. <div id="enable-section-numbers" />
  13749. <Info>**Protocol Revision**: draft</Info>
  13750. The Model Context Protocol (MCP) provides a standardized way for servers to expose
  13751. resources to clients. Resources allow servers to share data that provides context to
  13752. language models, such as files, database schemas, or application-specific information.
  13753. Each resource is uniquely identified by a
  13754. [URI](https://datatracker.ietf.org/doc/html/rfc3986).
  13755. ## User Interaction Model
  13756. Resources in MCP are designed to be **application-driven**, with host applications
  13757. determining how to incorporate context based on their needs.
  13758. For example, applications could:
  13759. * Expose resources through UI elements for explicit selection, in a tree or list view
  13760. * Allow the user to search through and filter available resources
  13761. * Implement automatic context inclusion, based on heuristics or the AI model's selection
  13762. ![Example of resource context picker](https://mintlify.s3.us-west-1.amazonaws.com/mcp/specification/draft/server/resource-picker.png)
  13763. However, implementations are free to expose resources through any interface pattern that
  13764. suits their needs—the protocol itself does not mandate any specific user
  13765. interaction model.
  13766. ## Capabilities
  13767. Servers that support resources **MUST** declare the `resources` capability:
  13768. ```json
  13769. {
  13770. "capabilities": {
  13771. "resources": {
  13772. "subscribe": true,
  13773. "listChanged": true
  13774. }
  13775. }
  13776. }
  13777. ```
  13778. The capability supports two optional features:
  13779. * `subscribe`: whether the client can subscribe to be notified of changes to individual
  13780. resources.
  13781. * `listChanged`: whether the server will emit notifications when the list of available
  13782. resources changes.
  13783. Both `subscribe` and `listChanged` are optional—servers can support neither,
  13784. either, or both:
  13785. ```json
  13786. {
  13787. "capabilities": {
  13788. "resources": {} // Neither feature supported
  13789. }
  13790. }
  13791. ```
  13792. ```json
  13793. {
  13794. "capabilities": {
  13795. "resources": {
  13796. "subscribe": true // Only subscriptions supported
  13797. }
  13798. }
  13799. }
  13800. ```
  13801. ```json
  13802. {
  13803. "capabilities": {
  13804. "resources": {
  13805. "listChanged": true // Only list change notifications supported
  13806. }
  13807. }
  13808. }
  13809. ```
  13810. ## Protocol Messages
  13811. ### Listing Resources
  13812. To discover available resources, clients send a `resources/list` request. This operation
  13813. supports [pagination](/specification/draft/server/utilities/pagination).
  13814. **Request:**
  13815. ```json
  13816. {
  13817. "jsonrpc": "2.0",
  13818. "id": 1,
  13819. "method": "resources/list",
  13820. "params": {
  13821. "cursor": "optional-cursor-value"
  13822. }
  13823. }
  13824. ```
  13825. **Response:**
  13826. ```json
  13827. {
  13828. "jsonrpc": "2.0",
  13829. "id": 1,
  13830. "result": {
  13831. "resources": [
  13832. {
  13833. "uri": "file:///project/src/main.rs",
  13834. "name": "main.rs",
  13835. "description": "Primary application entry point",
  13836. "mimeType": "text/x-rust"
  13837. }
  13838. ],
  13839. "nextCursor": "next-page-cursor"
  13840. }
  13841. }
  13842. ```
  13843. ### Reading Resources
  13844. To retrieve resource contents, clients send a `resources/read` request:
  13845. **Request:**
  13846. ```json
  13847. {
  13848. "jsonrpc": "2.0",
  13849. "id": 2,
  13850. "method": "resources/read",
  13851. "params": {
  13852. "uri": "file:///project/src/main.rs"
  13853. }
  13854. }
  13855. ```
  13856. **Response:**
  13857. ```json
  13858. {
  13859. "jsonrpc": "2.0",
  13860. "id": 2,
  13861. "result": {
  13862. "contents": [
  13863. {
  13864. "uri": "file:///project/src/main.rs",
  13865. "mimeType": "text/x-rust",
  13866. "text": "fn main() {\n println!(\"Hello world!\");\n}"
  13867. }
  13868. ]
  13869. }
  13870. }
  13871. ```
  13872. ### Resource Templates
  13873. Resource templates allow servers to expose parameterized resources using
  13874. [URI templates](https://datatracker.ietf.org/doc/html/rfc6570). Arguments may be
  13875. auto-completed through [the completion API](/specification/draft/server/utilities/completion).
  13876. **Request:**
  13877. ```json
  13878. {
  13879. "jsonrpc": "2.0",
  13880. "id": 3,
  13881. "method": "resources/templates/list"
  13882. }
  13883. ```
  13884. **Response:**
  13885. ```json
  13886. {
  13887. "jsonrpc": "2.0",
  13888. "id": 3,
  13889. "result": {
  13890. "resourceTemplates": [
  13891. {
  13892. "uriTemplate": "file:///{path}",
  13893. "name": "Project Files",
  13894. "description": "Access files in the project directory",
  13895. "mimeType": "application/octet-stream"
  13896. }
  13897. ]
  13898. }
  13899. }
  13900. ```
  13901. ### List Changed Notification
  13902. When the list of available resources changes, servers that declared the `listChanged`
  13903. capability **SHOULD** send a notification:
  13904. ```json
  13905. {
  13906. "jsonrpc": "2.0",
  13907. "method": "notifications/resources/list_changed"
  13908. }
  13909. ```
  13910. ### Subscriptions
  13911. The protocol supports optional subscriptions to resource changes. Clients can subscribe
  13912. to specific resources and receive notifications when they change:
  13913. **Subscribe Request:**
  13914. ```json
  13915. {
  13916. "jsonrpc": "2.0",
  13917. "id": 4,
  13918. "method": "resources/subscribe",
  13919. "params": {
  13920. "uri": "file:///project/src/main.rs"
  13921. }
  13922. }
  13923. ```
  13924. **Update Notification:**
  13925. ```json
  13926. {
  13927. "jsonrpc": "2.0",
  13928. "method": "notifications/resources/updated",
  13929. "params": {
  13930. "uri": "file:///project/src/main.rs"
  13931. }
  13932. }
  13933. ```
  13934. ## Message Flow
  13935. ```mermaid
  13936. sequenceDiagram
  13937. participant Client
  13938. participant Server
  13939. Note over Client,Server: Resource Discovery
  13940. Client->>Server: resources/list
  13941. Server-->>Client: List of resources
  13942. Note over Client,Server: Resource Access
  13943. Client->>Server: resources/read
  13944. Server-->>Client: Resource contents
  13945. Note over Client,Server: Subscriptions
  13946. Client->>Server: resources/subscribe
  13947. Server-->>Client: Subscription confirmed
  13948. Note over Client,Server: Updates
  13949. Server--)Client: notifications/resources/updated
  13950. Client->>Server: resources/read
  13951. Server-->>Client: Updated contents
  13952. ```
  13953. ## Data Types
  13954. ### Resource
  13955. A resource definition includes:
  13956. * `uri`: Unique identifier for the resource
  13957. * `name`: Human-readable name
  13958. * `description`: Optional description
  13959. * `mimeType`: Optional MIME type
  13960. * `size`: Optional size in bytes
  13961. ### Resource Contents
  13962. Resources can contain either text or binary data:
  13963. #### Text Content
  13964. ```json
  13965. {
  13966. "uri": "file:///example.txt",
  13967. "mimeType": "text/plain",
  13968. "text": "Resource content"
  13969. }
  13970. ```
  13971. #### Binary Content
  13972. ```json
  13973. {
  13974. "uri": "file:///example.png",
  13975. "mimeType": "image/png",
  13976. "blob": "base64-encoded-data"
  13977. }
  13978. ```
  13979. ## Common URI Schemes
  13980. The protocol defines several standard URI schemes. This list not
  13981. exhaustive—implementations are always free to use additional, custom URI schemes.
  13982. ### https\://
  13983. Used to represent a resource available on the web.
  13984. Servers **SHOULD** use this scheme only when the client is able to fetch and load the
  13985. resource directly from the web on its own—that is, it doesn’t need to read the resource
  13986. via the MCP server.
  13987. For other use cases, servers **SHOULD** prefer to use another URI scheme, or define a
  13988. custom one, even if the server will itself be downloading resource contents over the
  13989. internet.
  13990. ### file://
  13991. Used to identify resources that behave like a filesystem. However, the resources do not
  13992. need to map to an actual physical filesystem.
  13993. MCP servers **MAY** identify file:// resources with an
  13994. [XDG MIME type](https://specifications.freedesktop.org/shared-mime-info-spec/0.14/ar01s02.html#id-1.3.14),
  13995. like `inode/directory`, to represent non-regular files (such as directories) that don’t
  13996. otherwise have a standard MIME type.
  13997. ### git://
  13998. Git version control integration.
  13999. ### Custom URI Schemes
  14000. Custom URI schemes **MUST** be in accordance with [RFC3986](https://datatracker.ietf.org/doc/html/rfc3986),
  14001. taking the above guidance in to account.
  14002. ## Error Handling
  14003. Servers **SHOULD** return standard JSON-RPC errors for common failure cases:
  14004. * Resource not found: `-32002`
  14005. * Internal errors: `-32603`
  14006. Example error:
  14007. ```json
  14008. {
  14009. "jsonrpc": "2.0",
  14010. "id": 5,
  14011. "error": {
  14012. "code": -32002,
  14013. "message": "Resource not found",
  14014. "data": {
  14015. "uri": "file:///nonexistent.txt"
  14016. }
  14017. }
  14018. }
  14019. ```
  14020. ## Security Considerations
  14021. 1. Servers **MUST** validate all resource URIs
  14022. 2. Access controls **SHOULD** be implemented for sensitive resources
  14023. 3. Binary data **MUST** be properly encoded
  14024. 4. Resource permissions **SHOULD** be checked before operations
  14025. # Tools
  14026. Source: https://modelcontextprotocol.io/specification/draft/server/tools
  14027. <div id="enable-section-numbers" />
  14028. <Info>**Protocol Revision**: draft</Info>
  14029. The Model Context Protocol (MCP) allows servers to expose tools that can be invoked by
  14030. language models. Tools enable models to interact with external systems, such as querying
  14031. databases, calling APIs, or performing computations. Each tool is uniquely identified by
  14032. a name and includes metadata describing its schema.
  14033. ## User Interaction Model
  14034. Tools in MCP are designed to be **model-controlled**, meaning that the language model can
  14035. discover and invoke tools automatically based on its contextual understanding and the
  14036. user's prompts.
  14037. However, implementations are free to expose tools through any interface pattern that
  14038. suits their needs—the protocol itself does not mandate any specific user
  14039. interaction model.
  14040. <Warning>
  14041. For trust & safety and security, there **SHOULD** always
  14042. be a human in the loop with the ability to deny tool invocations.
  14043. Applications **SHOULD**:
  14044. * Provide UI that makes clear which tools are being exposed to the AI model
  14045. * Insert clear visual indicators when tools are invoked
  14046. * Present confirmation prompts to the user for operations, to ensure a human is in the
  14047. loop
  14048. </Warning>
  14049. ## Capabilities
  14050. Servers that support tools **MUST** declare the `tools` capability:
  14051. ```json
  14052. {
  14053. "capabilities": {
  14054. "tools": {
  14055. "listChanged": true
  14056. }
  14057. }
  14058. }
  14059. ```
  14060. `listChanged` indicates whether the server will emit notifications when the list of
  14061. available tools changes.
  14062. ## Protocol Messages
  14063. ### Listing Tools
  14064. To discover available tools, clients send a `tools/list` request. This operation supports
  14065. [pagination](/specification/draft/server/utilities/pagination).
  14066. **Request:**
  14067. ```json
  14068. {
  14069. "jsonrpc": "2.0",
  14070. "id": 1,
  14071. "method": "tools/list",
  14072. "params": {
  14073. "cursor": "optional-cursor-value"
  14074. }
  14075. }
  14076. ```
  14077. **Response:**
  14078. ```json
  14079. {
  14080. "jsonrpc": "2.0",
  14081. "id": 1,
  14082. "result": {
  14083. "tools": [
  14084. {
  14085. "name": "get_weather",
  14086. "description": "Get current weather information for a location",
  14087. "inputSchema": {
  14088. "type": "object",
  14089. "properties": {
  14090. "location": {
  14091. "type": "string",
  14092. "description": "City name or zip code"
  14093. }
  14094. },
  14095. "required": ["location"]
  14096. }
  14097. }
  14098. ],
  14099. "nextCursor": "next-page-cursor"
  14100. }
  14101. }
  14102. ```
  14103. ### Calling Tools
  14104. To invoke a tool, clients send a `tools/call` request:
  14105. **Request:**
  14106. ```json
  14107. {
  14108. "jsonrpc": "2.0",
  14109. "id": 2,
  14110. "method": "tools/call",
  14111. "params": {
  14112. "name": "get_weather",
  14113. "arguments": {
  14114. "location": "New York"
  14115. }
  14116. }
  14117. }
  14118. ```
  14119. **Response:**
  14120. ```json
  14121. {
  14122. "jsonrpc": "2.0",
  14123. "id": 2,
  14124. "result": {
  14125. "content": [
  14126. {
  14127. "type": "text",
  14128. "text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy"
  14129. }
  14130. ],
  14131. "isError": false
  14132. }
  14133. }
  14134. ```
  14135. ### List Changed Notification
  14136. When the list of available tools changes, servers that declared the `listChanged`
  14137. capability **SHOULD** send a notification:
  14138. ```json
  14139. {
  14140. "jsonrpc": "2.0",
  14141. "method": "notifications/tools/list_changed"
  14142. }
  14143. ```
  14144. ## Message Flow
  14145. ```mermaid
  14146. sequenceDiagram
  14147. participant LLM
  14148. participant Client
  14149. participant Server
  14150. Note over Client,Server: Discovery
  14151. Client->>Server: tools/list
  14152. Server-->>Client: List of tools
  14153. Note over Client,LLM: Tool Selection
  14154. LLM->>Client: Select tool to use
  14155. Note over Client,Server: Invocation
  14156. Client->>Server: tools/call
  14157. Server-->>Client: Tool result
  14158. Client->>LLM: Process result
  14159. Note over Client,Server: Updates
  14160. Server--)Client: tools/list_changed
  14161. Client->>Server: tools/list
  14162. Server-->>Client: Updated tools
  14163. ```
  14164. ## Data Types
  14165. ### Tool
  14166. A tool definition includes:
  14167. * `name`: Unique identifier for the tool
  14168. * `description`: Human-readable description of functionality
  14169. * `inputSchema`: JSON Schema defining expected parameters
  14170. * `outputSchema`: Optional JSON Schema defining expected output structure
  14171. * `annotations`: optional properties describing tool behavior
  14172. <Warning>
  14173. For trust & safety and security, clients **MUST** consider
  14174. tool annotations to be untrusted unless they come from trusted servers.
  14175. </Warning>
  14176. ### Tool Result
  14177. Tool results may contain [**structured**](#structured-content) or **unstructured** content.
  14178. **Unstructured** content is returned in the `content` field of a result, and can contain multiple content items of different types:
  14179. #### Text Content
  14180. ```json
  14181. {
  14182. "type": "text",
  14183. "text": "Tool result text"
  14184. }
  14185. ```
  14186. #### Image Content
  14187. ```json
  14188. {
  14189. "type": "image",
  14190. "data": "base64-encoded-data",
  14191. "mimeType": "image/png"
  14192. }
  14193. ```
  14194. #### Audio Content
  14195. ```json
  14196. {
  14197. "type": "audio",
  14198. "data": "base64-encoded-audio-data",
  14199. "mimeType": "audio/wav"
  14200. }
  14201. ```
  14202. #### Resource Links
  14203. A tool **MAY** return links to [Resources](/specification/draft/server/resources), to provide additional context
  14204. or data. In this case, the tool will return a URI that can be subscribed to or fetched by the client:
  14205. ```json
  14206. {
  14207. "type": "resource_link",
  14208. "uri": "file:///project/src/main.rs",
  14209. "name": "main.rs",
  14210. "description": "Primary application entry point",
  14211. "mimeType": "text/x-rust"
  14212. }
  14213. ```
  14214. <Info>
  14215. Resource links returned by tools are not guaranteed to appear in the results
  14216. of a `resources/list` request.
  14217. </Info>
  14218. #### Embedded Resources
  14219. [Resources](/specification/draft/server/resources) **MAY** be embedded to provide additional context
  14220. or data using a suitable [URI scheme](./resources#common-uri-schemes). Servers that use embedded resources **SHOULD** implement the `resources` capability:
  14221. ```json
  14222. {
  14223. "type": "resource",
  14224. "resource": {
  14225. "uri": "file:///project/src/main.rs",
  14226. "mimeType": "text/x-rust",
  14227. "text": "fn main() {\n println!(\"Hello world!\");\n}"
  14228. }
  14229. }
  14230. ```
  14231. #### Structured Content
  14232. **Structured** content is returned as a JSON object in the `structuredContent` field of a result.
  14233. For backwards compatibility, a tool that returns structured content SHOULD also return functionally equivalent unstructured content.
  14234. (For example, serialized JSON can be returned in a `TextContent` block.)
  14235. #### Output Schema
  14236. Tools may also provide an output schema for validation of structured results.
  14237. If an output schema is provided:
  14238. * Servers **MUST** provide structured results that conform to this schema.
  14239. * Clients **SHOULD** validate structured results against this schema.
  14240. Example tool with output schema:
  14241. ```json
  14242. {
  14243. "name": "get_weather_data",
  14244. "description": "Get current weather data for a location",
  14245. "inputSchema": {
  14246. "type": "object",
  14247. "properties": {
  14248. "location": {
  14249. "type": "string",
  14250. "description": "City name or zip code"
  14251. }
  14252. },
  14253. "required": ["location"]
  14254. },
  14255. "outputSchema": {
  14256. "type": "object",
  14257. "properties": {
  14258. "temperature": {
  14259. "type": "number",
  14260. "description": "Temperature in celsius"
  14261. },
  14262. "conditions": {
  14263. "type": "string",
  14264. "description": "Weather conditions description"
  14265. },
  14266. "humidity": {
  14267. "type": "number",
  14268. "description": "Humidity percentage"
  14269. }
  14270. },
  14271. "required": ["temperature", "conditions", "humidity"]
  14272. }
  14273. }
  14274. ```
  14275. Example valid response for this tool:
  14276. ```json
  14277. {
  14278. "jsonrpc": "2.0",
  14279. "id": 5,
  14280. "result": {
  14281. "content": [
  14282. {
  14283. "type": "text",
  14284. "text": "{\"temperature\": 22.5, \"conditions\": \"Partly cloudy\", \"humidity\": 65}"
  14285. }
  14286. ],
  14287. "structuredContent": {
  14288. "temperature": 22.5,
  14289. "conditions": "Partly cloudy",
  14290. "humidity": 65
  14291. }
  14292. }
  14293. }
  14294. ```
  14295. Providing an output schema helps clients and LLMs understand and properly handle structured tool outputs by:
  14296. * Enabling strict schema validation of responses
  14297. * Providing type information for better integration with programming languages
  14298. * Guiding clients and LLMs to properly parse and utilize the returned data
  14299. * Supporting better documentation and developer experience
  14300. ## Error Handling
  14301. Tools use two error reporting mechanisms:
  14302. 1. **Protocol Errors**: Standard JSON-RPC errors for issues like:
  14303. * Unknown tools
  14304. * Invalid arguments
  14305. * Server errors
  14306. 2. **Tool Execution Errors**: Reported in tool results with `isError: true`:
  14307. * API failures
  14308. * Invalid input data
  14309. * Business logic errors
  14310. Example protocol error:
  14311. ```json
  14312. {
  14313. "jsonrpc": "2.0",
  14314. "id": 3,
  14315. "error": {
  14316. "code": -32602,
  14317. "message": "Unknown tool: invalid_tool_name"
  14318. }
  14319. }
  14320. ```
  14321. Example tool execution error:
  14322. ```json
  14323. {
  14324. "jsonrpc": "2.0",
  14325. "id": 4,
  14326. "result": {
  14327. "content": [
  14328. {
  14329. "type": "text",
  14330. "text": "Failed to fetch weather data: API rate limit exceeded"
  14331. }
  14332. ],
  14333. "isError": true
  14334. }
  14335. }
  14336. ```
  14337. ## Security Considerations
  14338. 1. Servers **MUST**:
  14339. * Validate all tool inputs
  14340. * Implement proper access controls
  14341. * Rate limit tool invocations
  14342. * Sanitize tool outputs
  14343. 2. Clients **SHOULD**:
  14344. * Prompt for user confirmation on sensitive operations
  14345. * Show tool inputs to the user before calling the server, to avoid malicious or
  14346. accidental data exfiltration
  14347. * Validate tool results before passing to LLM
  14348. * Implement timeouts for tool calls
  14349. * Log tool usage for audit purposes
  14350. # Completion
  14351. Source: https://modelcontextprotocol.io/specification/draft/server/utilities/completion
  14352. <div id="enable-section-numbers" />
  14353. <Info>**Protocol Revision**: draft</Info>
  14354. The Model Context Protocol (MCP) provides a standardized way for servers to offer
  14355. argument autocompletion suggestions for prompts and resource URIs. This enables rich,
  14356. IDE-like experiences where users receive contextual suggestions while entering argument
  14357. values.
  14358. ## User Interaction Model
  14359. Completion in MCP is designed to support interactive user experiences similar to IDE code
  14360. completion.
  14361. For example, applications may show completion suggestions in a dropdown or popup menu as
  14362. users type, with the ability to filter and select from available options.
  14363. However, implementations are free to expose completion through any interface pattern that
  14364. suits their needs—the protocol itself does not mandate any specific user
  14365. interaction model.
  14366. ## Capabilities
  14367. Servers that support completions **MUST** declare the `completions` capability:
  14368. ```json
  14369. {
  14370. "capabilities": {
  14371. "completions": {}
  14372. }
  14373. }
  14374. ```
  14375. ## Protocol Messages
  14376. ### Requesting Completions
  14377. To get completion suggestions, clients send a `completion/complete` request specifying
  14378. what is being completed through a reference type:
  14379. **Request:**
  14380. ```json
  14381. {
  14382. "jsonrpc": "2.0",
  14383. "id": 1,
  14384. "method": "completion/complete",
  14385. "params": {
  14386. "ref": {
  14387. "type": "ref/prompt",
  14388. "name": "code_review"
  14389. },
  14390. "argument": {
  14391. "name": "language",
  14392. "value": "py"
  14393. }
  14394. }
  14395. }
  14396. ```
  14397. **Response:**
  14398. ```json
  14399. {
  14400. "jsonrpc": "2.0",
  14401. "id": 1,
  14402. "result": {
  14403. "completion": {
  14404. "values": ["python", "pytorch", "pyside"],
  14405. "total": 10,
  14406. "hasMore": true
  14407. }
  14408. }
  14409. }
  14410. ```
  14411. For prompts or URI templates with multiple arguments, clients should resolve them in the order they are presented by the server, and include each previous completion in the `context.arguments` object to provide context for subsequent requests.
  14412. **Request:**
  14413. ```json
  14414. {
  14415. "jsonrpc": "2.0",
  14416. "id": 1,
  14417. "method": "completion/complete",
  14418. "params": {
  14419. "ref": {
  14420. "type": "ref/prompt",
  14421. "name": "code_review"
  14422. },
  14423. "argument": {
  14424. "name": "framework",
  14425. "value": "fla"
  14426. },
  14427. "context": {
  14428. "arguments": {
  14429. "language": "python"
  14430. }
  14431. }
  14432. }
  14433. }
  14434. ```
  14435. **Response:**
  14436. ```json
  14437. {
  14438. "jsonrpc": "2.0",
  14439. "id": 1,
  14440. "result": {
  14441. "completion": {
  14442. "values": ["flask"],
  14443. "total": 1,
  14444. "hasMore": false
  14445. }
  14446. }
  14447. }
  14448. ```
  14449. ### Reference Types
  14450. The protocol supports two types of completion references:
  14451. | Type | Description | Example |
  14452. | -------------- | --------------------------- | --------------------------------------------------- |
  14453. | `ref/prompt` | References a prompt by name | `{"type": "ref/prompt", "name": "code_review"}` |
  14454. | `ref/resource` | References a resource URI | `{"type": "ref/resource", "uri": "file:///{path}"}` |
  14455. ### Completion Results
  14456. Servers return an array of completion values ranked by relevance, with:
  14457. * Maximum 100 items per response
  14458. * Optional total number of available matches
  14459. * Boolean indicating if additional results exist
  14460. ## Message Flow
  14461. ```mermaid
  14462. sequenceDiagram
  14463. participant Client
  14464. participant Server
  14465. Note over Client: User types argument
  14466. Client->>Server: completion/complete
  14467. Server-->>Client: Completion suggestions
  14468. Note over Client: User continues typing
  14469. Client->>Server: completion/complete
  14470. Server-->>Client: Refined suggestions
  14471. ```
  14472. ## Data Types
  14473. ### CompleteRequest
  14474. * `ref`: A `PromptReference` or `ResourceReference`
  14475. * `argument`: Object containing:
  14476. * `name`: Argument name
  14477. * `value`: Current value
  14478. * `context`: Object containing:
  14479. * `arguments`: A mapping of already-resolved argument names to their values.
  14480. ### CompleteResult
  14481. * `completion`: Object containing:
  14482. * `values`: Array of suggestions (max 100)
  14483. * `total`: Optional total matches
  14484. * `hasMore`: Additional results flag
  14485. ## Error Handling
  14486. Servers **SHOULD** return standard JSON-RPC errors for common failure cases:
  14487. * Method not found: `-32601` (Capability not supported)
  14488. * Invalid prompt name: `-32602` (Invalid params)
  14489. * Missing required arguments: `-32602` (Invalid params)
  14490. * Internal errors: `-32603` (Internal error)
  14491. ## Implementation Considerations
  14492. 1. Servers **SHOULD**:
  14493. * Return suggestions sorted by relevance
  14494. * Implement fuzzy matching where appropriate
  14495. * Rate limit completion requests
  14496. * Validate all inputs
  14497. 2. Clients **SHOULD**:
  14498. * Debounce rapid completion requests
  14499. * Cache completion results where appropriate
  14500. * Handle missing or partial results gracefully
  14501. ## Security
  14502. Implementations **MUST**:
  14503. * Validate all completion inputs
  14504. * Implement appropriate rate limiting
  14505. * Control access to sensitive suggestions
  14506. * Prevent completion-based information disclosure
  14507. # Logging
  14508. Source: https://modelcontextprotocol.io/specification/draft/server/utilities/logging
  14509. <div id="enable-section-numbers" />
  14510. <Info>**Protocol Revision**: draft</Info>
  14511. The Model Context Protocol (MCP) provides a standardized way for servers to send
  14512. structured log messages to clients. Clients can control logging verbosity by setting
  14513. minimum log levels, with servers sending notifications containing severity levels,
  14514. optional logger names, and arbitrary JSON-serializable data.
  14515. ## User Interaction Model
  14516. Implementations are free to expose logging through any interface pattern that suits their
  14517. needs—the protocol itself does not mandate any specific user interaction model.
  14518. ## Capabilities
  14519. Servers that emit log message notifications **MUST** declare the `logging` capability:
  14520. ```json
  14521. {
  14522. "capabilities": {
  14523. "logging": {}
  14524. }
  14525. }
  14526. ```
  14527. ## Log Levels
  14528. The protocol follows the standard syslog severity levels specified in
  14529. [RFC 5424](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1):
  14530. | Level | Description | Example Use Case |
  14531. | --------- | -------------------------------- | -------------------------- |
  14532. | debug | Detailed debugging information | Function entry/exit points |
  14533. | info | General informational messages | Operation progress updates |
  14534. | notice | Normal but significant events | Configuration changes |
  14535. | warning | Warning conditions | Deprecated feature usage |
  14536. | error | Error conditions | Operation failures |
  14537. | critical | Critical conditions | System component failures |
  14538. | alert | Action must be taken immediately | Data corruption detected |
  14539. | emergency | System is unusable | Complete system failure |
  14540. ## Protocol Messages
  14541. ### Setting Log Level
  14542. To configure the minimum log level, clients **MAY** send a `logging/setLevel` request:
  14543. **Request:**
  14544. ```json
  14545. {
  14546. "jsonrpc": "2.0",
  14547. "id": 1,
  14548. "method": "logging/setLevel",
  14549. "params": {
  14550. "level": "info"
  14551. }
  14552. }
  14553. ```
  14554. ### Log Message Notifications
  14555. Servers send log messages using `notifications/message` notifications:
  14556. ```json
  14557. {
  14558. "jsonrpc": "2.0",
  14559. "method": "notifications/message",
  14560. "params": {
  14561. "level": "error",
  14562. "logger": "database",
  14563. "data": {
  14564. "error": "Connection failed",
  14565. "details": {
  14566. "host": "localhost",
  14567. "port": 5432
  14568. }
  14569. }
  14570. }
  14571. }
  14572. ```
  14573. ## Message Flow
  14574. ```mermaid
  14575. sequenceDiagram
  14576. participant Client
  14577. participant Server
  14578. Note over Client,Server: Configure Logging
  14579. Client->>Server: logging/setLevel (info)
  14580. Server-->>Client: Empty Result
  14581. Note over Client,Server: Server Activity
  14582. Server--)Client: notifications/message (info)
  14583. Server--)Client: notifications/message (warning)
  14584. Server--)Client: notifications/message (error)
  14585. Note over Client,Server: Level Change
  14586. Client->>Server: logging/setLevel (error)
  14587. Server-->>Client: Empty Result
  14588. Note over Server: Only sends error level<br/>and above
  14589. ```
  14590. ## Error Handling
  14591. Servers **SHOULD** return standard JSON-RPC errors for common failure cases:
  14592. * Invalid log level: `-32602` (Invalid params)
  14593. * Configuration errors: `-32603` (Internal error)
  14594. ## Implementation Considerations
  14595. 1. Servers **SHOULD**:
  14596. * Rate limit log messages
  14597. * Include relevant context in data field
  14598. * Use consistent logger names
  14599. * Remove sensitive information
  14600. 2. Clients **MAY**:
  14601. * Present log messages in the UI
  14602. * Implement log filtering/search
  14603. * Display severity visually
  14604. * Persist log messages
  14605. ## Security
  14606. 1. Log messages **MUST NOT** contain:
  14607. * Credentials or secrets
  14608. * Personal identifying information
  14609. * Internal system details that could aid attacks
  14610. 2. Implementations **SHOULD**:
  14611. * Rate limit messages
  14612. * Validate all data fields
  14613. * Control log access
  14614. * Monitor for sensitive content
  14615. # Pagination
  14616. Source: https://modelcontextprotocol.io/specification/draft/server/utilities/pagination
  14617. <div id="enable-section-numbers" />
  14618. <Info>**Protocol Revision**: draft</Info>
  14619. The Model Context Protocol (MCP) supports paginating list operations that may return
  14620. large result sets. Pagination allows servers to yield results in smaller chunks rather
  14621. than all at once.
  14622. Pagination is especially important when connecting to external services over the
  14623. internet, but also useful for local integrations to avoid performance issues with large
  14624. data sets.
  14625. ## Pagination Model
  14626. Pagination in MCP uses an opaque cursor-based approach, instead of numbered pages.
  14627. * The **cursor** is an opaque string token, representing a position in the result set
  14628. * **Page size** is determined by the server, and clients **MUST NOT** assume a fixed page
  14629. size
  14630. ## Response Format
  14631. Pagination starts when the server sends a **response** that includes:
  14632. * The current page of results
  14633. * An optional `nextCursor` field if more results exist
  14634. ```json
  14635. {
  14636. "jsonrpc": "2.0",
  14637. "id": "123",
  14638. "result": {
  14639. "resources": [...],
  14640. "nextCursor": "eyJwYWdlIjogM30="
  14641. }
  14642. }
  14643. ```
  14644. ## Request Format
  14645. After receiving a cursor, the client can *continue* paginating by issuing a request
  14646. including that cursor:
  14647. ```json
  14648. {
  14649. "jsonrpc": "2.0",
  14650. "method": "resources/list",
  14651. "params": {
  14652. "cursor": "eyJwYWdlIjogMn0="
  14653. }
  14654. }
  14655. ```
  14656. ## Pagination Flow
  14657. ```mermaid
  14658. sequenceDiagram
  14659. participant Client
  14660. participant Server
  14661. Client->>Server: List Request (no cursor)
  14662. loop Pagination Loop
  14663. Server-->>Client: Page of results + nextCursor
  14664. Client->>Server: List Request (with cursor)
  14665. end
  14666. ```
  14667. ## Operations Supporting Pagination
  14668. The following MCP operations support pagination:
  14669. * `resources/list` - List available resources
  14670. * `resources/templates/list` - List resource templates
  14671. * `prompts/list` - List available prompts
  14672. * `tools/list` - List available tools
  14673. ## Implementation Guidelines
  14674. 1. Servers **SHOULD**:
  14675. * Provide stable cursors
  14676. * Handle invalid cursors gracefully
  14677. 2. Clients **SHOULD**:
  14678. * Treat a missing `nextCursor` as the end of results
  14679. * Support both paginated and non-paginated flows
  14680. 3. Clients **MUST** treat cursors as opaque tokens:
  14681. * Don't make assumptions about cursor format
  14682. * Don't attempt to parse or modify cursors
  14683. * Don't persist cursors across sessions
  14684. ## Error Handling
  14685. Invalid cursors **SHOULD** result in an error with code -32602 (Invalid params).
  14686. # Versioning
  14687. Source: https://modelcontextprotocol.io/specification/versioning
  14688. The Model Context Protocol uses string-based version identifiers following the format
  14689. `YYYY-MM-DD`, to indicate the last date backwards incompatible changes were made.
  14690. <Info>
  14691. The protocol version will *not* be incremented when the
  14692. protocol is updated, as long as the changes maintain backwards compatibility. This allows
  14693. for incremental improvements while preserving interoperability.
  14694. </Info>
  14695. ## Revisions
  14696. Revisions may be marked as:
  14697. * **Draft**: in-progress specifications, not yet ready for consumption.
  14698. * **Current**: the current protocol version, which is ready for use and may continue to
  14699. receive backwards compatible changes.
  14700. * **Final**: past, complete specifications that will not be changed.
  14701. The **current** protocol version is [**2025-03-26**](/specification/2025-03-26/).
  14702. ## Negotiation
  14703. Version negotiation happens during
  14704. [initialization](/specification/2025-03-26/basic/lifecycle#initialization). Clients and
  14705. servers **MAY** support multiple protocol versions simultaneously, but they **MUST**
  14706. agree on a single version to use for the session.
  14707. The protocol provides appropriate error handling if version negotiation fails, allowing
  14708. clients to gracefully terminate connections when they cannot find a version compatible
  14709. with the server.
  14710. # Building MCP with LLMs
  14711. Source: https://modelcontextprotocol.io/tutorials/building-mcp-with-llms
  14712. Speed up your MCP development using LLMs such as Claude!
  14713. This guide will help you use LLMs to help you build custom Model Context Protocol (MCP) servers and clients. We'll be focusing on Claude for this tutorial, but you can do this with any frontier LLM.
  14714. ## Preparing the documentation
  14715. Before starting, gather the necessary documentation to help Claude understand MCP:
  14716. 1. Visit [https://modelcontextprotocol.io/llms-full.txt](https://modelcontextprotocol.io/llms-full.txt) and copy the full documentation text
  14717. 2. Navigate to either the [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) or [Python SDK repository](https://github.com/modelcontextprotocol/python-sdk)
  14718. 3. Copy the README files and other relevant documentation
  14719. 4. Paste these documents into your conversation with Claude
  14720. ## Describing your server
  14721. Once you've provided the documentation, clearly describe to Claude what kind of server you want to build. Be specific about:
  14722. * What resources your server will expose
  14723. * What tools it will provide
  14724. * Any prompts it should offer
  14725. * What external systems it needs to interact with
  14726. For example:
  14727. ```
  14728. Build an MCP server that:
  14729. - Connects to my company's PostgreSQL database
  14730. - Exposes table schemas as resources
  14731. - Provides tools for running read-only SQL queries
  14732. - Includes prompts for common data analysis tasks
  14733. ```
  14734. ## Working with Claude
  14735. When working with Claude on MCP servers:
  14736. 1. Start with the core functionality first, then iterate to add more features
  14737. 2. Ask Claude to explain any parts of the code you don't understand
  14738. 3. Request modifications or improvements as needed
  14739. 4. Have Claude help you test the server and handle edge cases
  14740. Claude can help implement all the key MCP features:
  14741. * Resource management and exposure
  14742. * Tool definitions and implementations
  14743. * Prompt templates and handlers
  14744. * Error handling and logging
  14745. * Connection and transport setup
  14746. ## Best practices
  14747. When building MCP servers with Claude:
  14748. * Break down complex servers into smaller pieces
  14749. * Test each component thoroughly before moving on
  14750. * Keep security in mind - validate inputs and limit access appropriately
  14751. * Document your code well for future maintenance
  14752. * Follow MCP protocol specifications carefully
  14753. ## Next steps
  14754. After Claude helps you build your server:
  14755. 1. Review the generated code carefully
  14756. 2. Test the server with the MCP Inspector tool
  14757. 3. Connect it to Claude.app or other MCP clients
  14758. 4. Iterate based on real usage and feedback
  14759. Remember that Claude can help you modify and improve your server as requirements change over time.
  14760. Need more guidance? Just ask Claude specific questions about implementing MCP features or troubleshooting issues that arise.