Showing posts with label Web Api. Show all posts
Showing posts with label Web Api. Show all posts

Tuesday, February 24, 2026

Create a Simple API for MCP Server Tool Client Setup

Ask: Create a API project with some sample endpoints and these endpoints should be consumed by some AI agent using MCP standards.

To Solve this use case, we will utilize .Net project library with MCP standards included. 

For example purpose, i will create below endpoints

Endpoints
1) GET /hello
     Description: Returns default greeting.
     Body (JSON): { "message": "Hello, World!" }

2) GET /hello/{name}
    Description: Returns greeting for provided name.
    Path param: name (string)
    Body (JSON): { "message": "Hello, {name}!" }

3) POST /hello
    Description: Returns greeting using provided JSON payload.
    Request body (JSON): { "name": "<string>" }
    Body (JSON): { "message": "Hello, <string>!" }

Example validation: if name missing or empty return 400 Bad Request with { "error": "name is required" }


Steps to Create Project:

1. Go to Visual Studio Developer command and Type below command to add .Net core project template

     dotnet new install Microsoft.McpServer.ProjectTemplates



2. Go to Visual Studio IDE and add new project then select "MCP server App" as template then complete project creation




3. Open Github Copilot using your credentials, type the prompt as below "Convert this project as MCP Server and MCP Tool based for the Hello World Sample usage for below endpoints

Endpoints
1) GET /hello
     Description: Returns default greeting.
     Body (JSON): { "message": "Hello, World!" }

2) GET /hello/{name}
    Description: Returns greeting for provided name.
    Path param: name (string)
    Body (JSON): { "message": "Hello, {name}!" }

3) POST /hello
    Description: Returns greeting using provided JSON payload.
    Request body (JSON): { "name": "<string>" }
    Body (JSON): { "message": "Hello, <string>!" }.

Additionally add new web project as MCP client to consume these endpoints"




4. Wait for some time the project would have been ready with Github. If there are any build errors or correction, you can keep continue with Github copilot in chat. Note: choose options as Agent and your preferred model to get code generated automatically.

5. Go to Project solution and add existing project, you should see in same folder other projects would have been added. Include those into solution, so now you can see API project for MCP server, Web Project for MCP Client

6. Now on the api endpoint, go to /swagger and you can see all the MCP tools default endpoints 

                                             

7. Now we can call the /tools to see existing endpoint, hello_world is the one we created




8. Go to /start-server to trigger the MCP server to initiate locally


9. Now call the tool as /call-tool to trigger the endpoint and pass the payload as 

{
  "toolName": "hello_world",
  "parameters": "balaji"
}

you will see the output as 

{
  "result": "Hello, balaji!"
}



10. Now your MCP server tool setup is ready to consume by other agents as hello world example. 













Saturday, April 25, 2015

MVC & WebAPI - Model Binder

There are some specific cases in order to use model binder to MVC and WebAPI in same project.

Here i will explain step by step to implement MVC and WebAPI Model Binders

What is Model Binder?

In some cases, we should do common operations for all actions inside controller. So in that case we can add model binder and pass as parameter to actions. In below example UserModel class sent as Model Binder

public ActionResult Index([ModelBinder]UserModel model)

{
...
}

Implementing Model Binder for MVC

MVC uses different namespace such as System.Web.Mvc. So Model Binder class also should use the same.

Step 1:

Create UserModel class as required. Here we can add our required properties. In this example, i am going to display UserId and UserName

public class UserModel
    {
        public string UserId { get; set; }
        public string UserName { get; set; }

    }

Step 2:

Create custom ModelBinder class which can be implemented from System.Web.Mvc.IModelBinder as below. Here i created as partial for merging with WebAPI. If you dont need WebAPI then just have it as normal class


public partial class UserModelBinder : System.Web.Mvc.IModelBinder
    {
        public object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(UserModel))
            {
                return null;
            }

            UserModel userModel = new UserModel();

            var userId = HttpContext.Current.User.Identity.GetUserId();

            if (!string.IsNullOrEmpty(userId))
            {
/// Create your custom logics to fill the other required details. In this example i can fill username
            }
            return userModel;
        }
    }

Step 3:

Register this Custom ModelBinder class into Global.asax.cs file

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Model binder for MVC controller usermodel
            ModelBinders.Binders.Add(typeof(UserModel), new UserModelBinder());

        }

Step 4:

Use this custom model binder in action methods of MVC controller

public ActionResult Index([System.Web.Http.ModelBinding.ModelBinder]UserModel model)

{
...
 //Write your logic to do with UserModel class object
}


Thats all for MVC Model Binder.


Implementing Model Binder for WebAPI

WebAPI cannot be worked with MVC model binder. So we need to create differently. Step 1 to create UserModel is same. So i will go from Step 2

Step 2:

Create Custom Model Binder for WebAPI as follows. Here IModelBinder uses System.Web.Http.ModelBinding.

using Microsoft.AspNet.Identity;
using System.Web;
using System.Web.Http;
using System.Web.Http.ModelBinding;

public partial class UserModelBinder : IModelBinder
    {
        public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(UserModel))
            {
                return false;
            }

            UserModel userModel = new UserModel();

            var userId = HttpContext.Current.User.Identity.GetUserId();

            if (!string.IsNullOrEmpty(userId))
            {
               //Your logic to fill usermodel class and assign to binding context’s model
                bindingContext.Model = userModel;
                return true;
            }

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Error in model binding");
            return false;
        }

    }


Step 3:

Create ModelBinderProvider class as follows. It is going to be register with configuration. Here ModelBinderProvider uses namespace System.Web.Http.ModelBinding..

public class UserModelBinderProvider : ModelBinderProvider
    {
        private System.Type type;
        private UserModelBinder userModelBinder;

        public UserModelBinderProvider(System.Type type, UserModelBinder userModelBinder)
        {
            this.type = type;
            this.userModelBinder = userModelBinder;
        }

        public override IModelBinder GetBinder(HttpConfiguration configuration, System.Type modelType)
        {
            if (modelType == type)
            {
                return userModelBinder;
            }

            return null;
        }

    }


Step 4:

Register ModelBinderProvider in Global.asax.cs file under WebApiConfig register method

public static class WebApiConfig

    {
    public static void Register(HttpConfiguration config)
        {
         var provider = new UserModelBinderProvider(typeof(UserModel), new UserModelBinder());

         config.Services.Insert(typeof(ModelBinderProvider), 0, provider);


Step 5:

Use in APIController action methods as follows

[HttpGet]
        public string GetUserName([ModelBinder]UserModel model)
        {
              return model.UserName;
  }

Thats all for WebAPI Model Binder.


Tuesday, March 12, 2013

MVC4 - Web Api make work of Put and Delete methods


To use the PUT and DELETE verbs with the Web API in MVC4 
Open ApplicationHost.config from following path
%userprofile%\Documents\IISExpress\config\applicationhost.config 
Add the verbs to the ExtensionlessUrl handler as follows:
Change this line:
<add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0"/>
to:
<add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0"/>
You can see we have added PUT, DELETE in Verb.

In addition to the above you should ensure WebDAV is not interfering with your requests. This can be done by commenting out the following lines from applicationhost.config.
<add name="WebDAVModule" image="%IIS_BIN%\webdav.dll" />
<add name="WebDAVModule" /> 
<add name="WebDAV" path="*" verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK" modules="WebDAVModule" resourceType="Unspecified" requireAccess="None" />
Also be aware that the default Web API convention is that your method name should be the same as the invoked HTTP verb. For example if you're sending an HTTP delete request your method, by default, should be named Delete.